<file_sep>package fr.dashboard.server;

import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;

@RestController
public class Gith {

    /**
     * Liste les repositories Github recherchés
     * @param search Nom du repository recherché
     * @return Liste des repositories correspondant à la recherche
     */
    @RequestMapping({"/githubRepoSearch"})
    public static ArrayList<ArrayList<String>> githubRepoSearch(@RequestParam("rechearch") String search) {
        ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
        ArrayList<String> tmp = new ArrayList<String>();
        RepositoryService service = new RepositoryService();
        try {
            for (Repository repo : service.getRepositories(search)) {
                tmp = new ArrayList<String>();
                tmp.add(repo.getName());
                tmp.add(repo.getUrl());
                tmp.add(repo.getHomepage());
                tmp.add(repo.getDescription());
                tmp.add(repo.getOwner().getName());
                tmp.add(repo.getOwner().getUrl());
            }
            results.add(tmp);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return results;
    }
}<file_sep>package fr.dashboard.server;

//import org.springframework.data.annotation.Id;

public class MyUser {

/*    @Id
    public String id;

    public String email;
    public String password;

    public MyUser() {

    }

    public MyUser(String firstName, String lastName) {
        this.email = firstName;
        this.password = <PASSWORD>;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%s, firstName='%s', lastName='%s']",
                id, email, password);
    }*/
}<file_sep>buildscript {
	repositories {
		maven { url "https://repo.spring.io/libs-milestone" }
		maven { url "https://repo.spring.io/libs-snapshot" }
		mavenLocal()
	}
	dependencies {
		classpath('gradle.plugin.com.palantir.gradle.docker:gradle-docker:0.13.0')
	}
}

plugins {
	id 'org.springframework.boot' version '2.2.0.RELEASE'
	id 'io.spring.dependency-management' version '1.0.8.RELEASE'
	id 'java'
}

group = 'fr.dashboard.server'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
	maven { url "https://repo.spring.io/milestone" }
	maven { url "https://repo.spring.io/libs-milestone" }
}

dependencies {

	implementation 'org.springframework.boot:spring-boot-starter-web'

	compile("org.springframework.boot:spring-boot-starter-thymeleaf")
	compile("org.springframework.boot:spring-boot-devtools")
	compile("org.springframework.boot:spring-boot-starter-test")
    compile 'org.twitter4j:twitter4j-stream:4.0.6'
	compile 'org.springframework.social:spring-social-facebook:3.0.0.M1'
	compile 'org.springframework.social:spring-social-core:2.0.0.M2'
	compile	'org.springframework.social:spring-social-config:2.0.0.M2'
	implementation 'org.eclipse.mylyn.github:org.eclipse.egit.github.core:1.1.2'
	compile group: 'org.facebook4j', name: 'facebook4j-core', version: '2.4.13'
	implementation 'org.mariadb.jdbc:mariadb-java-client:2.1.2'

	// https://mvnrepository.com/artifact/com.google.api-client/google-api-client
	compile group: 'com.google.api-client', name: 'google-api-client', version: '1.25.0'

	// https://mvnrepository.com/artifact/com.google.apis/google-api-services-youtube
	compile group: 'com.google.apis', name: 'google-api-services-youtube', version: 'v3-rev212-1.25.0'

	compile group: 'com.google.apis', name: 'google-api-services-youtubeAnalytics', version: 'v1-rev14-1.13.2-beta'

	// https://mvnrepository.com/artifact/com.google.apis/google-api-services-youtubereporting
	compile group: 'com.google.apis', name: 'google-api-services-youtubereporting', version: 'v1-rev1-1.20.0'

	// https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty
	compile("com.google.oauth-client:google-oauth-client-jetty:1.25.0") {
		exclude group: 'org.mortbay.jetty', module: 'servlet-api'
	}
// https://mvnrepository.com/artifact/com.google.http-client/google-http-client-jackson2
	compile group: 'com.google.http-client', name: 'google-http-client-jackson2', version: '1.25.0'

	// https://mvnrepository.com/artifact/com.google.collections/google-collections
	compile group: 'com.google.collections', name: 'google-collections', version: '1.0'

	implementation ("org.springframework.boot:spring-boot-starter-web:2.0.1.RELEASE")
	implementation ("org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.0.0.RELEASE")
	implementation ("org.webjars:js-cookie:2.1.0")
	implementation ("org.webjars:jquery:2.1.1")
    implementation("org.springframework.boot:spring-boot-starter-security")
	implementation ("org.webjars:bootstrap:3.2.0")
	implementation ("org.webjars:webjars-locator-core:0.35")
	implementation ("org.springframework.boot:spring-boot-configuration-processor:2.0.1.RELEASE")


	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

bootJar {
	mainClassName = 'fr.dashboard.server.DashboardServer'
}

apply plugin: 'com.palantir.docker'

task unpack(type: Copy) {
	dependsOn bootJar
	from(zipTree(tasks.bootJar.outputs.files.singleFile))
	into("build/dependency")
}

docker {
	name "${project.group}/${bootJar.baseName}"
	copySpec.from(tasks.unpack.outputs).into("dependency")
	buildArgs(['DEPENDENCY': "dependency"])
}<file_sep>package fr.dashboard.server;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.DatagramSocket;
import java.net.InetAddress;


/**
 * Donne accès à la page about.json
 */
@RestController
public class About {

    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
    /**
     * Lit le fichier about.json, et l'actualise l'IP ainsi que le temps actuel avant de le mapper
     * @return about.json
     * @throws Exception
     */
    @RequestMapping({"/about.json"})
    public static String about() throws Exception {
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream is = classloader.getResourceAsStream("about.json");
        String to_find = "\"current_time\": ";
        String to_find_2 = "\"host\": ";
        String data = convertStreamToString(is);
        StringBuilder tmp = new StringBuilder(data);
        tmp.insert(data.indexOf(to_find) + to_find.length(), System.currentTimeMillis());
        try(final DatagramSocket socket = new DatagramSocket()){
            socket.connect(InetAddress.getByName("8.8.8.8"), 8080);
            String ip = socket.getLocalAddress().getHostAddress();
            tmp.insert(30, "\"" + ip + "\"");
        }
        return tmp.toString();
    }
}<file_sep>rootProject.name = 'epidashboard'
<file_sep>package fr.dashboard.server.Twitter;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class TwitTweetSearch {

    public static Twitter getTwitterinstance() {
        /**
         * if not using properties file, we can set access token by following way
         */
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true)
                .setOAuthConsumerKey("")
                .setOAuthConsumerSecret("")
                .setOAuthAccessToken("")
                .setOAuthAccessTokenSecret("");
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getSingleton();

/*
        Twitter twitter = TwitterFactory.getSingleton();
*/
        return twitter;

    }
    @RequestMapping({"/twitterTweetCreation"})
    public static String createTweet(@RequestParam("rechearch") String tweet) throws TwitterException {
        Twitter twitter = getTwitterinstance();
        System.out.println(tweet);
        Status status = twitter.updateStatus(tweet);
        return status.getText();
    }

    @RequestMapping({"/twitterTimeline"})
    public static List<String> getTimeLine() throws TwitterException {
        Twitter twitter = getTwitterinstance();
        List<Status> statuses = twitter.getHomeTimeline();
        return statuses.stream().map(
                item -> item.getText()).collect(
                Collectors.toList());
    }

    @RequestMapping({"/twitterSendMessage"})
    public static String sendDirectMessage(@RequestParam("name") String recipientName, @RequestParam("rechearch") String msg) throws TwitterException {
        Twitter twitter = getTwitterinstance();
        DirectMessage message = twitter.sendDirectMessage(recipientName, msg);
        return message.getText();
    }

    @RequestMapping({"/twitterTweetSearch"})
    public static List<String> searchtweets(@RequestParam("rechearch") String search) throws TwitterException {
        Twitter twitter = getTwitterinstance();
        Query query = new Query(search);
        QueryResult result = twitter.search(query);
        List<Status> statuses = result.getTweets();
        return statuses.stream().map(
                item -> item.getText()).collect(
                Collectors.toList());
    }

/*
    @RequestMapping({"/twitter"})
    public static List<String> searchtweets() throws TwitterException {
        Twitter twitter = getTwitterinstance();
        Query query = new Query("source:twitter4j baeldung");
        QueryResult result = twitter.search(query);
        List<Status> statuses = result.getTweets();
        System.out.println(statuses.stream().map(
                item -> item.getText()).collect(
                Collectors.toList()));
        return statuses.stream().map(
                item -> item.getText()).collect(
                Collectors.toList());
    }
*/

    public static void streamFeed() {

        StatusListener listener = new StatusListener(){

            @Override
            public void onException(Exception e) {
                e.printStackTrace();
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice arg) {
                System.out.println("Got a status deletion notice id:" + arg.getStatusId());
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            @Override
            public void onStallWarning(StallWarning warning) {
                System.out.println("Got stall warning:" + warning);
            }

            @Override
            public void onStatus(Status status) {
                System.out.println(status.getUser().getName() + " : " + status.getText());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }
        };

        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

        twitterStream.addListener(listener);

        twitterStream.sample();

    }

}
<file_sep># Dashboard

Application web permettant de gérer divers services contenant chacun au moins 1 widgets.

## Technologie utilisé
- Java
- Html
- Css
- Jquery
- Ajax
- Docker
- Spring boot
- IntelliJ


## Installation

Conditions préalables
- docker
- Java 1.8

Fedora

```bash
sudo yum install docker-ce
```
or
```bash
sudo dnf install docker-ce
```


Ubuntu

```bash
sudo apt-get install docker-ce
```


## Docker

Run docker 

```python
cd DEV_dashboard_2019

sudo docker-compose build
```
Run the Docker container:

```python
sudo docker-compose up
```

### Compile sans docker.
Pour ceux qui ne veulent pas docker, vous pouvez run le programme comme ci-dessous:

```python
rm -rf build && ./gradlew build bootJar && java -jar build/libs/epidashboard-0.0.1-SNAPSHOT.jar > .log
```

## Voir le résultat
    http://localhost:8080

## Authentifications disponible
- Github
- Facebook
- Google
- Youtube
- Twitter
- Login/password


## Services disponible(12)
- Météo
- Cinéma
- Steam
- Reddit
- Twitter
- Deezer
- MemeCat
- Giphy
- Youtube
- Github
- IpLocalize
- Twitch

## Widgets disponible(19)
- Météo: actuelle
- Météo: prévision
- Cinéma: Film à l'affiche
- Cinéma: Recherche de film
- Steam: Nombre de joueurs connecté
- Steam: Recherche de news de jeux
- Reddit: Recherche de subreddit
- Twitter: Recherche de Tweets
- Twitter: Recherche de users
- Twitter: Possibilité de Tweeter
- Deezer: Recherche et lancement de musique
- MemeCat: Affichage de meme de cat aléatoire par thème
- Giphy: Recherche de Gif
- Youtube: Recherche de chaine youtube
- Youtube: Recherche de vidéo youtube
- Github: Recherche de repos
- IpLocalize: localisation des ip
- Twitch: Affiche N top streamers les plus recherchés
- Twitch: Affiche N top steams les plus recherchés

## Développement
Projet Epitech réalisé sur une période de 1 mois en groupe de 2 (<NAME> et <NAME>).<file_sep>version: '3'
services:
    server:
        build: epidashboard
        ports:
            - "8080:8080"
        depends_on:
            - db
        environment:
            - MYSQL_HOST=db
            - MYSQL_PORT=3306
    db:
        image: mariadb
        restart: always
        container_name: db
        environment:
            - MYSQL_DATABASE=dashboard
            - MYSQL_ROOT_PASSWORD=<PASSWORD>
        ports:
            - "3307:3306"
        volumes:
            - ./mysql-dump:/docker-entrypoint-initdb.d
            - mysql-db:/var/lib/mysql

volumes:
    mysql-db: