Commit d1b13275 authored by Szabolcs Gyurko's avatar Szabolcs Gyurko
Browse files

Added push messaging code to send notification when download is finished.

parent e1657f7e
Pipeline #350 failed with stage
in 60 minutes and 5 seconds
package actors
import java.security.cert.X509Certificate
import akka.actor.UntypedAbstractActor
import javax.inject.{Inject, Singleton}
import org.apache.http.NameValuePair
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
import org.apache.http.ssl.SSLContexts
import org.slf4j.LoggerFactory
import sget2.PushMessageEvent
import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer
@Singleton
class PushMessageHandler @Inject() (private val configuration: play.api.Configuration) extends UntypedAbstractActor {
private val Logger = LoggerFactory.getLogger(getClass)
@scala.throws[Throwable](classOf[Throwable])
override def onReceive(message: Any): Unit = {
message match {
case p: PushMessageEvent
handlePushMessage(p)
case _
}
}
private def handlePushMessage(pushMessageEvent: PushMessageEvent): Unit = {
val pushMessaging = configuration.underlying.getString("sget2.pushMessaging")
if (pushMessaging != null && pushMessaging.toBoolean) {
Logger.info("Sending push message with download completed details using pushover service")
val host = configuration.underlying.getString("sget2.pushConfig.host")
val token = configuration.underlying.getString("sget2.pushConfig.token")
val user = configuration.underlying.getString("sget2.pushConfig.user")
// Build a HTTP client
val sslConnectionSocketFactory = new SSLConnectionSocketFactory(SSLContexts.custom()
.loadTrustMaterial(null, (chain: Array[X509Certificate], authType: String) => true).build())
val requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(5000).build()
val httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
.disableContentCompression()
.setSSLSocketFactory(sslConnectionSocketFactory).build()
// Set up the form params
val html = if (pushMessageEvent.html) "1" else "0"
val params = new ListBuffer[NameValuePair]()
params += new BasicNameValuePair("token", token)
params += new BasicNameValuePair("user", user)
params += new BasicNameValuePair("html", html)
params += new BasicNameValuePair("title", pushMessageEvent.title)
params += new BasicNameValuePair("message", pushMessageEvent.message)
if (pushMessageEvent.url != null)
params += new BasicNameValuePair("url", pushMessageEvent.url)
if (pushMessageEvent.urlTitle != null)
params += new BasicNameValuePair("url_title", pushMessageEvent.urlTitle)
try {
// Create the POST message
val method = new HttpPost(host)
method.setEntity(new UrlEncodedFormEntity(params.toList.asJava))
// Fire & forget
httpClient.execute(method)
httpClient.close()
} catch {
case e: Exception
Logger.warn(s"Error communicating to ${host}, exception: ${e.getClass.getSimpleName}: ${e.getMessage}")
} finally {
httpClient.close()
}
}
}
}
......@@ -3,7 +3,7 @@ package actors
import akka.actor.UntypedAbstractActor
import javax.inject.{Inject, Singleton}
import org.slf4j.LoggerFactory
import sget2.{JobFinishedEvent, SGet2}
import sget2.{JobFinishedEvent, PushMessageEvent, SGet2}
/**
* Created by sgyurko on 25/08/2016.
......@@ -24,5 +24,6 @@ class QueueManager @Inject() (private val sget2: SGet2) extends UntypedAbstractA
private def jobFinished(event: JobFinishedEvent) = {
Logger.info("A job finished. Trying to start remaining jobs.")
sget2.downloadQueue.start()
sget2.postEvent(PushMessageEvent("Download complete", s"Job ID ${event.job.id} is finished. Downloaded filename is: ${event.job.path}", null, null))
}
}
......@@ -94,7 +94,7 @@ abstract class AbstractWorker(protected val downloadJob: DownloadJob, protected
} finally {
downloadJob.alive = false
sget2.postEvent(PersistEvent(forceSave = true))
sget2.postEvent(JobFinishedEvent())
sget2.postEvent(JobFinishedEvent(downloadJob))
}
}
}
......@@ -4,5 +4,6 @@ package sget2
* Created by sgyurko on 25/08/2016.
*/
sealed trait SGet2Event
final case class JobFinishedEvent() extends SGet2Event
final case class JobFinishedEvent(job: DownloadJob) extends SGet2Event
final case class PersistEvent(forceSave: Boolean = false) extends SGet2Event
final case class PushMessageEvent(title: String, message: String, url: String, urlTitle: String, html: Boolean = true) extends SGet2Event
package sget2
import actors.{DataPersister, QueueManager}
import actors.{DataPersister, PushMessageHandler, QueueManager}
import com.google.inject.AbstractModule
import play.api.libs.concurrent.AkkaGuiceSupport
......@@ -12,5 +12,6 @@ class SGet2Module extends AbstractModule with AkkaGuiceSupport {
bind(classOf[SGet2Startup]).asEagerSingleton()
bindActor[DataPersister]("DataPersister")
bindActor[QueueManager]("QueueManager")
bindActor[PushMessageHandler]("PushMessageHandler")
}
}
......@@ -14,13 +14,15 @@ import scala.concurrent.Future
@Singleton
class SGet2Startup @Inject() (private val sget2: SGet2, val lifecycle: ApplicationLifecycle,
@Named("DataPersister") private val persister: ActorRef,
@Named("QueueManager") private val queueManager: ActorRef) {
@Named("QueueManager") private val queueManager: ActorRef,
@Named("PushMessageHandler") private val pushMessageHandler: ActorRef) {
private val Logger = LoggerFactory.getLogger(getClass)
Logger.info("Starting SGet2")
sget2.subscribeTopic(persister)
sget2.subscribeTopic(queueManager)
sget2.subscribeTopic(pushMessageHandler)
lifecycle.addStopHook(() Future {
Logger.info("Stopping SGet2")
......
......@@ -11,7 +11,7 @@ import org.apache.http.client.methods.{HttpGet, HttpHead}
import org.apache.http.client.utils.{URIBuilder, URLEncodedUtils}
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.impl.client.{BasicCredentialsProvider, HttpClients}
import org.apache.http.ssl.{SSLContexts, TrustStrategy}
import org.apache.http.ssl.SSLContexts
import org.slf4j.LoggerFactory
import sget2.{AbstractWorker, AbstractWorkerThread, DownloadJob, SGet2}
......@@ -23,9 +23,7 @@ class HttpWorker (override protected val downloadJob: DownloadJob,
override protected val sget2: SGet2) extends AbstractWorker(downloadJob, sget2) {
private val Logger = LoggerFactory.getLogger(getClass)
val sslConnectionSocketFactory = new SSLConnectionSocketFactory(SSLContexts.custom()
.loadTrustMaterial(null, new TrustStrategy{
override def isTrusted(chain: Array[X509Certificate], authType: String): Boolean = true
}).build())
.loadTrustMaterial(null, (chain: Array[X509Certificate], authType: String) => true).build())
override def getArtifactName(url: URL): String = {
val requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(5000).build()
......@@ -43,7 +41,11 @@ class HttpWorker (override protected val downloadJob: DownloadJob,
credentialsProvider.setCredentials(
new AuthScope(url.getHost, port, url.getHost),
new UsernamePasswordCredentials(downloadJob.username.get, downloadJob.password.get))
httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(requestConfig).build()
httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultRequestConfig(requestConfig)
.disableContentCompression()
.setSSLSocketFactory(sslConnectionSocketFactory).build()
}
val httpResponse = httpClient.execute(method)
......
name := "sget2"
version := "1.3.2"
version := "1.4"
lazy val `sget2` = (project in file(".")).enablePlugins(PlayScala)
......
......@@ -69,6 +69,15 @@ play.filters.hosts {
allowed = ["."]
}
sget2 {
pushMessaging = true
pushConfig {
host = "https://api.pushover.net/1/messages.json"
# token = "valid_token"
# user = "valid_user"
}
}
# Logger
# ~~~~~
# You can also configure logback (http://logback.qos.ch/),
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment