-
-
Save kopax/3f178165c6a7023f3610f62afe4b611a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kopaxgroup.api.userManagement.job; | |
import com.github.redouane59.twitter.dto.tweet.MediaCategory; | |
import com.github.redouane59.twitter.dto.tweet.TweetV1; | |
import com.github.redouane59.twitter.dto.tweet.UploadMediaResponse; | |
import com.kopaxgroup.api.core.domain.LocalFile; | |
import com.kopaxgroup.api.core.domain.LocalFileDTO; | |
import com.kopaxgroup.api.core.service.LocalFileService; | |
import com.kopaxgroup.api.userManagement.config.context.TwitterServiceGenerator; | |
import com.kopaxgroup.api.userManagement.domain.*; | |
import com.kopaxgroup.api.userManagement.service.*; | |
import com.kopaxgroup.api.userManagement.service.common.UserService; | |
import org.quartz.*; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.context.annotation.Lazy; | |
import org.springframework.scheduling.quartz.QuartzJobBean; | |
import org.springframework.web.multipart.MultipartFile; | |
import java.io.*; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import java.nio.file.Paths; | |
import java.util.*; | |
public class CronTweetBotJob extends QuartzJobBean implements InterruptableJob { | |
private static final Logger logger = LoggerFactory.getLogger(CronTweetJob.class); | |
private volatile boolean toStopFlag = true; | |
@Lazy | |
@Autowired | |
TweetService tweetService; | |
@Lazy | |
@Autowired | |
UserService userService; | |
@Lazy | |
@Autowired | |
TwitterServiceGenerator generator; | |
@Lazy | |
@Autowired | |
TwitterAccountService twitterAccountService; | |
@Lazy | |
@Autowired | |
SimpleTriggerService simpleTriggerService; | |
@Lazy | |
@Autowired | |
TwitterUserService twitterUserService; | |
@Lazy | |
@Autowired | |
TweetBotService tweetBotService; | |
@Lazy | |
@Autowired | |
LocalFileService localFileService; | |
@Override | |
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { | |
JobKey key = jobExecutionContext.getJobDetail().getKey(); | |
logger.info("Cron Job started with key :" + key.getName() + ", Group :" + key.getGroup() + " , Thread Name :" + Thread.currentThread().getName() + " ,Time now :" + new Date()); | |
logger.info("======================================"); | |
logger.info("Accessing annotation example: " + simpleTriggerService.getAllJobs(TweetBotService.TRIGGER_GROUP)); | |
List<Map<String, Object>> list = simpleTriggerService.getAllJobs(TweetBotService.TRIGGER_GROUP); | |
logger.info("Job list :" + list); | |
logger.info("======================================"); | |
//*********** For retrieving stored key-value pairs ***********/ | |
JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap(); | |
Long tweetBotId = dataMap.getLong("id"); | |
logger.info("TweetBotId:" + tweetBotId); | |
while (toStopFlag) { | |
try { | |
logger.info("Tweet bot cron job Running... Thread Name :" + Thread.currentThread().getName()); | |
TweetBot bot = tweetBotService.get(tweetBotId); | |
TwitterAccount twitterAccount = twitterAccountService.get(bot.getAccountId()); | |
TwitterClient twitterClient = twitterAccountService.createTwitterClient(twitterAccount); | |
List<TweetV1> resultList = twitterClient.searchForTweetsV1(bot); | |
ArrayList<TweetV1> filteredList = new ArrayList<>(); | |
if (resultList.size() > 0) { | |
int cursor = 0; | |
while ((filteredList.size() < bot.getDesiredNbTweet() && cursor < resultList.size())) { | |
TweetV1 tweet = resultList.get(cursor); | |
if ( | |
bot.getMinimumLikeCount() <= tweet.getLikeCount() && | |
bot.getMinimumRetweetCount() <= tweet.getRetweetCount() && | |
bot.getMinimumReplyCount() <= tweet.getReplyCount() | |
) { | |
filteredList.add(tweet); | |
} | |
cursor += 1; | |
} | |
if (filteredList.size() > 0) { | |
for (TweetV1 tweet : filteredList) { | |
Collection<String> actions = bot.getActions(); | |
if (null != bot.getIsRandom() && bot.getIsRandom()) { | |
Random rand = new Random(); | |
int randomIndex = rand.nextInt(bot.getActions().size()); | |
actions = Collections.singletonList(bot.getActions().get(randomIndex)); | |
} | |
for (String action : actions) { | |
switch (action) { | |
case TweetBot.ACTION_LIKE: | |
twitterClient.likeTweet(tweet.getId()); | |
break; | |
case TweetBot.ACTION_RETWEET: | |
twitterClient.retweetTweet(tweet.getId()); | |
break; | |
case TweetBot.ACTION_FOLLOW: | |
twitterClient.followV1(tweet.getUser().getId()); | |
break; | |
} | |
} | |
if (bot.getReplyRatio() > 0 && (Math.random() * 10) < bot.getReplyRatio()) { | |
Random rand = new Random(); | |
int randomIndex = rand.nextInt(bot.getReplies().size()); | |
String status = bot.getReplies().get(randomIndex); | |
List<String> mediaIds = new ArrayList<>(); | |
if (bot.getGiphyRatio() > 0 && (Math.random() * 10) < bot.getGiphyRatio()) { | |
List<String> giphyIdList = new ArrayList<>(); | |
for (String url : bot.getGiphy()) { | |
String outputPath = downloadFromUrl(new URL(url), tweet.getId() + ".gif"); | |
File file = new File(outputPath); | |
if (file.exists()) { | |
UploadMediaResponse uploadMediaResponse = twitterClient.uploadMedia(file, MediaCategory.TWEET_IMAGE); | |
if (null != uploadMediaResponse.getMediaId()) { | |
giphyIdList.add(uploadMediaResponse.getMediaId()); | |
} | |
file.delete(); | |
} | |
} | |
if (null != bot.getIsRandomGiphy() && bot.getIsRandomGiphy()) { | |
Random randGiphy = new Random(); | |
int randomGiphyIndex = randGiphy.nextInt(bot.getGiphy().size()); | |
giphyIdList = Collections.singletonList(giphyIdList.get(randomGiphyIndex)); | |
} | |
mediaIds.addAll(giphyIdList); | |
} | |
if (bot.getImageRatio() > 0 && (Math.random() * 10) < bot.getImageRatio()) { | |
List<String> imageIdList = new ArrayList<>(); | |
LocalFileDTO cond = new LocalFileDTO(); | |
cond.setIds(bot.getLocalFileUploadIdList()); | |
List<LocalFile> localFileList = localFileService.findBasicAll(cond); | |
for (LocalFile localFile : localFileList) { | |
File file = new File(Paths.get(localFile.getPath(), localFile.getId().toString(), localFile.getName()).toString()); | |
UploadMediaResponse uploadMediaResponse = twitterClient.uploadMedia(file, MediaCategory.TWEET_IMAGE); | |
if (null != uploadMediaResponse.getMediaId()) { | |
imageIdList.add(uploadMediaResponse.getMediaId()); | |
} | |
} | |
if (null != bot.getIsRandomFiles() && bot.getIsRandomFiles()) { | |
Random randFile = new Random(); | |
int randomFileIndex = randFile.nextInt(bot.getLocalFileUploadIdList().size()); | |
imageIdList = Collections.singletonList(imageIdList.get(randomFileIndex)); | |
} | |
mediaIds.addAll(imageIdList); | |
} | |
twitterClient.postTweet(status, tweet.getId(), String.join(",", mediaIds)); | |
} | |
} | |
} else { | |
logger.info("No search results match for Tweet Bot " + tweetBotId); | |
} | |
} else { | |
logger.info("No search results for Tweet Bot " + tweetBotId); | |
} | |
simpleTriggerService.stopJob(key.getGroup(), key.getName()); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
logger.info("Thread: " + Thread.currentThread().getName() + " stopped."); | |
} | |
@Override | |
public void interrupt() throws UnableToInterruptJobException { | |
logger.info("Stopping thread... "); | |
toStopFlag = false; | |
} | |
public static String downloadFromUrl(URL url, String localFilename) throws IOException { | |
String tempDir = System.getProperty("java.io.tmpdir"); | |
String outputPath = tempDir + "/" + localFilename; | |
byte[] b = new byte[1]; | |
URLConnection urlConnection = url.openConnection(); | |
urlConnection.connect(); | |
DataInputStream di = new DataInputStream(urlConnection.getInputStream()); | |
FileOutputStream fo = new FileOutputStream(outputPath); | |
while (-1 != di.read(b, 0, 1)) | |
fo.write(b, 0, 1); | |
di.close(); | |
fo.close(); | |
return outputPath; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment