11 Commits
1.4.1 ... 1.8

Author SHA1 Message Date
Pijus Kamandulis
9a65746fd4 Update go.yml 2020-02-25 21:44:43 +02:00
Pijus Kamandulis
70c605a696 Merge pull request #6 from intracomof/master
Download videos by hashtag; limit option; get just json data
2020-02-25 21:33:57 +02:00
alexpin
208bffb846 error handling 2020-02-25 21:16:57 +02:00
alexpin
7b9b7688a1 formatter 2020-02-25 21:03:06 +02:00
intracomof
e77c904f89 Merge branch 'master' into master 2020-02-25 21:01:43 +02:00
alexpin
68612282ee default limit value updated; WaitReady(video) removed 2020-02-25 20:55:56 +02:00
Pijus Kamandulis
7a691ad32d TTDL-5 Added better error handling 2020-02-25 20:12:01 +02:00
alexpin
b6bb470064 formatter 2020-02-25 01:01:10 +02:00
alexpin
f724f0f2a2 Download videos by hashtag; get json data without video downloading; limit option 2020-02-25 00:56:19 +02:00
Pijus Kamandulis
1b3f985f42 Improved status output
Added `-quiet` flag

Move out error messages to separate file
2020-02-08 02:52:26 +02:00
Pijus Kamandulis
673bbe1340 TTDL-3 Add deadline flag 2020-01-30 19:05:33 +02:00
28 changed files with 498 additions and 231 deletions

View File

@@ -1,5 +1,5 @@
name: tiktok-dl_CI
on: [push]
on: [push, pull_request]
jobs:
build:
strategy:

1
.gitignore vendored
View File

@@ -5,3 +5,4 @@ downloads
*.exe
tiktok-dl
batch_file.txt
debug.log

View File

@@ -20,6 +20,10 @@ Clone this repository and run `go build` to build the executable.
* `-output some_directory` - Output path (default "./downloads")
* `-metadata` - Write video metadata to a .json file
* `-batch-file` - File containing URLs/Usernames to download, one value per line. Lines starting with '#', are considered as comments and ignored.
* `-deadline` - Sets the timout for scraper logic in seconds (used as a workaround for context deadline exceeded error) (default 1500)
* `-quiet` - Supress output
* `-json` - Returns whole data, that was scraped from TikTok, in json
* `-limit` - Sets the max count of video that will be downloaded (default infinity)
## Acknowledgments
This software uses the **chromedp** for web scraping, it can be found here: https://github.com/chromedp/chromedp \

View File

@@ -0,0 +1,114 @@
package client
import (
"context"
"errors"
"github.com/chromedp/chromedp"
"io/ioutil"
"log"
"os"
"strings"
"time"
config "../models/config"
utils "../utils"
)
// GetMusicUploads - Get all uploads by given music
func executeClientAction(url string, jsAction string) (string, error) {
dir, err := ioutil.TempDir("", "chromedp-example")
if err != nil {
return "", err
}
defer os.RemoveAll(dir)
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.DisableGPU,
chromedp.UserDataDir(dir),
chromedp.Flag("headless", !config.Config.Debug),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
ctx, cancel := chromedp.NewContext(
allocCtx,
chromedp.WithLogf(log.Printf),
)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, time.Duration(config.Config.Deadline)*time.Second)
defer cancel()
jsOutput, err := runScrapeWithInfo(ctx, jsAction, url)
if strings.HasPrefix(jsOutput, "\"ERR:") {
err = errors.New(jsOutput)
}
return jsOutput, err
}
func runScrapeQuiet(ctx context.Context, jsAction string, url string) (string, error) {
var jsOutput string
if err := chromedp.Run(ctx,
// Navigate to user's page
chromedp.Navigate(url),
// Execute url grabber script
chromedp.EvaluateAsDevTools(utils.ReadFileAsString("scraper.js"), &jsOutput),
chromedp.EvaluateAsDevTools(jsAction, &jsOutput),
// Wait until custom js finishes
chromedp.WaitVisible(`video_urls`),
// Grab url links from our element
chromedp.InnerHTML(`video_urls`, &jsOutput),
); err != nil {
return "", err
}
return jsOutput, nil
}
func runScrapeWithInfo(ctx context.Context, jsAction string, url string) (string, error) {
var jsOutput string
if err := chromedp.Run(ctx,
// Navigate to user's page
chromedp.Navigate(url),
// Execute url grabber script
chromedp.EvaluateAsDevTools(utils.ReadFileAsString("scraper.js"), &jsOutput),
chromedp.EvaluateAsDevTools(jsAction, &jsOutput),
); err != nil {
return "", err
}
for {
if err := chromedp.Run(ctx, chromedp.EvaluateAsDevTools("currentState.preloadCount.toString()", &jsOutput)); err != nil {
return "", err
}
if jsOutput != "0" {
utils.Logf("\rPreloading... %s items have been founded.", jsOutput)
} else {
utils.Logf("\rPreloading...")
}
if err := chromedp.Run(ctx, chromedp.EvaluateAsDevTools("currentState.finished.toString()", &jsOutput)); err != nil {
return "", err
}
if jsOutput == "true" {
break
}
time.Sleep(50 * time.Millisecond)
}
utils.Log("\nRetrieving items...")
if err := chromedp.Run(ctx,
// Wait until custom js finishes
chromedp.WaitVisible(`video_urls`),
// Grab url links from our element
chromedp.InnerHTML(`video_urls`, &jsOutput),
); err != nil {
return "", err
}
return jsOutput, nil
}

View File

@@ -0,0 +1,26 @@
package client
import (
models "../models"
config "../models/config"
"fmt"
)
// GetUserUploads - Get all uploads marked with given hashtag
func GetHashtagUploads(hashtagURL string) ([]models.Upload, error) {
jsMethod := fmt.Sprintf("bootstrapIteratingVideos(%d)", config.Config.Limit)
actionOutput, err := executeClientAction(hashtagURL, jsMethod)
if err != nil {
return nil, err
}
return models.ParseUploads(actionOutput), nil
}
func GetHashtagUploadsJson(hashtagURL string) (string, error) {
jsMethod := fmt.Sprintf("bootstrapIteratingVideos(%d)", config.Config.Limit)
actionOutput, err := executeClientAction(hashtagURL, jsMethod)
if err != nil {
return "", err
}
return actionOutput, nil
}

View File

@@ -1,58 +1,26 @@
package client
import (
"context"
"github.com/chromedp/chromedp"
"io/ioutil"
"log"
"os"
"time"
models "../models"
utils "../utils"
config "../models/config"
"fmt"
)
// GetMusicUploads - Get all uploads by given music
func GetMusicUploads(url string) []models.Upload {
dir, err := ioutil.TempDir("", "chromedp-example")
func GetMusicUploads(url string) ([]models.Upload, error) {
jsMethod := fmt.Sprintf("bootstrapIteratingVideos(%d)", config.Config.Limit)
actionOutput, err := executeClientAction(url, jsMethod)
if err != nil {
panic(err)
return nil, err
}
defer os.RemoveAll(dir)
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.DisableGPU,
chromedp.UserDataDir(dir),
chromedp.Flag("headless", !models.Config.Debug),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
ctx, cancel := chromedp.NewContext(
allocCtx,
chromedp.WithLogf(log.Printf),
)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, 1500*time.Second)
defer cancel()
var jsOutput string
err = chromedp.Run(ctx,
// Navigate to user's page
chromedp.Navigate(url),
// Execute url grabber script
chromedp.EvaluateAsDevTools(utils.ReadFileAsString("scraper.js"), &jsOutput),
chromedp.EvaluateAsDevTools("bootstrapIteratingVideos()", &jsOutput),
// Wait until custom js finishes
chromedp.WaitVisible(`video_urls`),
// Grab url links from our element
chromedp.InnerHTML(`video_urls`, &jsOutput),
)
if err != nil {
log.Fatal(err)
}
return models.ParseUploads(jsOutput)
return models.ParseUploads(actionOutput), nil
}
func GetMusicUploadsJson(url string) (string, error) {
jsMethod := fmt.Sprintf("bootstrapIteratingVideos(%d)", config.Config.Limit)
actionOutput, err := executeClientAction(url, jsMethod)
if err != nil {
return "", err
}
return actionOutput, nil
}

View File

@@ -1,58 +1,26 @@
package client
import (
"context"
"github.com/chromedp/chromedp"
"io/ioutil"
"log"
"os"
"time"
models "../models"
utils "../utils"
config "../models/config"
"fmt"
)
// GetUserUploads - Get all uploads by user
func GetUserUploads(username string) []models.Upload {
dir, err := ioutil.TempDir("", "chromedp-example")
func GetUserUploads(username string) ([]models.Upload, error) {
jsMethod := fmt.Sprintf("bootstrapIteratingVideos(%d)", config.Config.Limit)
actionOutput, err := executeClientAction(`https://www.tiktok.com/@`+username, jsMethod)
if err != nil {
panic(err)
return nil, err
}
defer os.RemoveAll(dir)
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.DisableGPU,
chromedp.UserDataDir(dir),
chromedp.Flag("headless", !models.Config.Debug),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
ctx, cancel := chromedp.NewContext(
allocCtx,
chromedp.WithLogf(log.Printf),
)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, 1500*time.Second)
defer cancel()
var jsOutput string
err = chromedp.Run(ctx,
// Navigate to user's page
chromedp.Navigate(`https://www.tiktok.com/@`+username),
// Execute url grabber script
chromedp.EvaluateAsDevTools(utils.ReadFileAsString("scraper.js"), &jsOutput),
chromedp.EvaluateAsDevTools("bootstrapIteratingVideos()", &jsOutput),
// Wait until custom js finishes
chromedp.WaitVisible(`video_urls`),
// Grab url links from our element
chromedp.InnerHTML(`video_urls`, &jsOutput),
)
if err != nil {
log.Fatal(err)
}
return models.ParseUploads(jsOutput)
return models.ParseUploads(actionOutput), nil
}
func GetUserUploadsJson(username string) (string, error) {
jsMethod := fmt.Sprintf("bootstrapIteratingVideos(%d)", config.Config.Limit)
actionOutput, err := executeClientAction(`https://www.tiktok.com/@`+username, jsMethod)
if err != nil {
return "", err
}
return actionOutput, nil
}

View File

@@ -1,58 +1,14 @@
package client
import (
"context"
"github.com/chromedp/chromedp"
"io/ioutil"
"log"
"os"
"time"
models "../models"
utils "../utils"
)
// GetVideoDetails - returns details of video
func GetVideoDetails(videoURL string) models.Upload {
dir, err := ioutil.TempDir("", "chromedp-example")
func GetVideoDetails(videoURL string) (models.Upload, error) {
actionOutput, err := executeClientAction(videoURL, "bootstrapGetCurrentVideo()")
if err != nil {
panic(err)
return models.Upload{}, err
}
defer os.RemoveAll(dir)
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.DisableGPU,
chromedp.UserDataDir(dir),
chromedp.Flag("headless", !models.Config.Debug),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
ctx, cancel := chromedp.NewContext(
allocCtx,
chromedp.WithLogf(log.Printf),
)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, 1500*time.Second)
defer cancel()
var jsOutput string
err = chromedp.Run(ctx,
// Navigate to user's page
chromedp.Navigate(videoURL),
// Execute url grabber script
chromedp.EvaluateAsDevTools(utils.ReadFileAsString("scraper.js"), &jsOutput),
chromedp.EvaluateAsDevTools("bootstrapGetCurrentVideo()", &jsOutput),
// Wait until custom js finishes
chromedp.WaitVisible(`video_urls`),
// Grab url links from our element
chromedp.InnerHTML(`video_urls`, &jsOutput),
)
if err != nil {
log.Fatal(err)
}
return models.ParseUpload(jsOutput)
return models.ParseUpload(actionOutput), nil
}

View File

@@ -1,14 +1,14 @@
package main
import (
models "./models"
config "./models/config"
workflows "./workflows"
)
func main() {
models.GetConfig()
url := models.Config.URL
batchFilePath := models.Config.BatchFilePath
config.GetConfig()
url := config.Config.URL
batchFilePath := config.Config.BatchFilePath
// Batch file
if workflows.CanUseDownloadBatchFile(batchFilePath) {

View File

@@ -1,11 +1,9 @@
package models
package config
import (
"flag"
"fmt"
"os"
"regexp"
"strings"
)
// Config - Runtime configuration
@@ -15,6 +13,10 @@ var Config struct {
BatchFilePath string
Debug bool
MetaData bool
Quiet bool
Deadline int
Limit int
JSONOnly bool
}
// GetConfig - Returns Config object
@@ -23,6 +25,10 @@ func GetConfig() {
batchFilePath := flag.String("batch-file", "", "File containing URLs/Usernames to download, one value per line. Lines starting with '#', are considered as comments and ignored.")
debug := flag.Bool("debug", false, "Enables debug mode")
metadata := flag.Bool("metadata", false, "Write video metadata to a .json file")
quiet := flag.Bool("quiet", false, "Supress output")
deadline := flag.Int("deadline", 1500, "Sets the timout for scraper logic in seconds (used as a workaround for 'context deadline exceeded' error)")
limit := flag.Int("limit", 0, "Sets the videos count limit (useful when there too many videos from the user or by hashtag)")
jsonOnly := flag.Bool("json", false, "Just get JSON data from scraper (without video downloading)")
flag.Parse()
args := flag.Args()
@@ -41,23 +47,11 @@ func GetConfig() {
Config.BatchFilePath = *batchFilePath
Config.Debug = *debug
Config.MetaData = *metadata
}
// GetUsername - Get's username from passed URL param
func GetUsername() string {
return GetUsernameFromString(Config.URL)
}
// GetUsernameFromString - Get's username from passed param
func GetUsernameFromString(str string) string {
if match := strings.Contains(str, "/"); !match { // Not url
return strings.Replace(str, "@", "", -1)
Config.Quiet = *quiet
if *jsonOnly {
Config.Quiet = true
}
if match, _ := regexp.MatchString(".+tiktok\\.com/@.+", str); match { // URL
stripedSuffix := strings.Split(str, "@")[1]
return strings.Split(stripedSuffix, "/")[0]
}
panic("Could not recognise URL format")
Config.Deadline = *deadline
Config.Limit = *limit
Config.JSONOnly = *jsonOnly
}

View File

@@ -1,8 +1,9 @@
package models
import (
res "../resources"
utils "../utils"
"encoding/json"
"fmt"
"os"
"strings"
)
@@ -46,21 +47,16 @@ func (u Upload) GetUploadID() string {
func (u Upload) WriteToFile(outputPath string) {
bytes, err := json.Marshal(u)
if err != nil {
fmt.Printf("Could not serialize json for video: %s", u.GetUploadID())
fmt.Println()
utils.Logf(res.ErrorCouldNotSerializeJSON, u.GetUploadID())
panic(err)
}
// Create the file
out, err := os.Create(outputPath)
if err != nil {
panic(err)
}
utils.CheckErr(err)
defer out.Close()
// Write to file
_, err = out.Write(bytes)
if err != nil {
panic(err)
}
utils.CheckErr(err)
}

View File

@@ -3,7 +3,7 @@
"version": "0.0.1",
"scripts": {
"install-dependencies": "go get -v -t -d ./...",
"test": "go test -v ./models",
"test": "go test -v ./models && go test -v ./utils",
"clean": "rm -rf out",
"build:scraper": "node node_modules/terser/bin/terser -c -m -- scraper.js > out/scraper.js",
"build:app": "go build -o out/ -v .",

13
resources/strings.go Normal file
View File

@@ -0,0 +1,13 @@
package resources
// ErrorCouldNotSerializeJSON -
var ErrorCouldNotSerializeJSON = "Could not serialize json for video: %s\n"
// ErrorCouldNotRecogniseURL -
var ErrorCouldNotRecogniseURL = "Could not recognise URL format of string %s"
// ErrorCouldNotGetUserUploads -
var ErrorCouldNotGetUserUploads = "Failed to get user uploads: %s\n"
// ErrorPathNotFound -
var ErrorPathNotFound = "File path %s not found."

View File

@@ -1,7 +1,7 @@
optStrings = {
selectors: {
feedLoading: 'div.tiktok-loading.feed-loading',
modalArrowLeft: 'div.video-card-modal > div > img.arrow-right',
modalArrowRight: 'div.video-card-modal > div > img.arrow-right',
modalClose: '.video-card-modal > div > div.close',
modalPlayer: 'div > div > main > div.video-card-modal > div > div.video-card-big > div.video-card-container > div > div > video',
modalShareInput: '.copy-link-container > input',
@@ -17,6 +17,7 @@ optStrings = {
classes: {
feedVideoItem: 'video-feed-item-wrapper',
modalCloseDisabled: 'disabled',
titleMessage: 'title',
},
tags: {
resultTag: 'video_urls',
@@ -25,13 +26,38 @@ optStrings = {
attributes: {
src: "src",
},
tiktokMessages: [
"Couldn't find this account",
"No videos yet",
"Video currently unavailable",
],
};
currentState = {
preloadCount: 0,
finished: false,
limit: 0
};
checkForErrors = function() {
var titles = document.getElementsByClassName(optStrings.classes.titleMessage);
debugger;
if (titles && titles.length) {
var error = Array.from(titles).find(x => optStrings.tiktokMessages.includes(x.textContent)).textContent;
if (error) {
createVidUrlElement("ERR: " + error);
return true;
}
}
return false;
};
createVidUrlElement = function(outputObj) {
var urlSetElement = document.createElement(optStrings.tags.resultTag);
urlSetElement.innerText = JSON.stringify(outputObj);
document.getElementsByTagName(optStrings.tags.resultParentTag)[0].appendChild(urlSetElement);
}
currentState.finished = true;
};
buldVidUrlArray = function(finishCallback) {
var feedItem = document.getElementsByClassName(optStrings.classes.feedVideoItem)[0];
@@ -40,8 +66,14 @@ buldVidUrlArray = function(finishCallback) {
var videoArray = [];
var intervalID = window.setInterval(x => {
videoArray.push(getCurrentModalVideo());
var arrowRight = document.querySelectorAll(optStrings.selectors.modalArrowLeft)[0];
if(currentState.limit > 0) {
if (videoArray.length >= currentState.limit) {
window.clearInterval(intervalID);
document.querySelector(optStrings.selectors.modalClose).click();
finishCallback(videoArray);
}
}
var arrowRight = document.querySelectorAll(optStrings.selectors.modalArrowRight)[0];
if (arrowRight.classList.contains(optStrings.classes.modalCloseDisabled)) {
window.clearInterval(intervalID);
document.querySelector(optStrings.selectors.modalClose).click();
@@ -72,9 +104,10 @@ getCurrentModalVideo = function() {
link: soundHref,
},
};
}
};
getCurrentVideo = function() {
if(checkForErrors()) return;
var player = document.querySelector(optStrings.selectors.videoPlayer);
var vidUrl = player.getAttribute(optStrings.attributes.src);
var shareLink = document.querySelector(optStrings.selectors.videoShareInput).value;
@@ -94,14 +127,25 @@ getCurrentVideo = function() {
link: soundHref,
},
};
}
};
scrollWhileNew = function(finishCallback) {
var state = { count: 0 };
var intervalID = window.setInterval(x => {
var oldCount = state.count;
state.count = document.getElementsByClassName(optStrings.classes.feedVideoItem).length;
if(currentState.limit > 0) {
if (currentState.preloadCount >= currentState.limit || state.count >= currentState.limit) {
finishCallback(createVidUrlElement);
window.clearInterval(intervalID);
}
}
if(checkForErrors()) {
window.clearInterval(intervalID);
return;
}
if (oldCount !== state.count) {
currentState.preloadCount = state.count;
window.scrollTo(0, document.body.scrollHeight);
} else {
if (document.querySelector(optStrings.selectors.feedLoading)) {
@@ -114,7 +158,8 @@ scrollWhileNew = function(finishCallback) {
}, 1000);
};
bootstrapIteratingVideos = function() {
bootstrapIteratingVideos = function(limit) {
currentState.limit = limit;
scrollWhileNew(buldVidUrlArray);
return 'bootstrapIteratingVideos';
};
@@ -123,7 +168,7 @@ bootstrapGetCurrentVideo = function() {
var video = getCurrentVideo();
createVidUrlElement(video);
return 'bootstrapGetCurrentVideo';
}
};
init = () => {
const newProto = navigator.__proto__;

12
utils/checkErr.go Normal file
View File

@@ -0,0 +1,12 @@
package utils
import (
"log"
)
// CheckErr - Checks if error and log
func CheckErr(err error) {
if err != nil {
log.Fatal(err)
}
}

View File

@@ -10,22 +10,15 @@ import (
func DownloadFile(outputPath string, url string) {
// Get the data
resp, err := http.Get(url)
if err != nil {
panic(err)
}
CheckErr(err)
defer resp.Body.Close()
// Create the file
out, err := os.Create(outputPath)
if err != nil {
panic(err)
}
CheckErr(err)
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
panic(err)
}
CheckErr(err)
}

View File

@@ -37,9 +37,7 @@ func ReadFileToString(path string) string {
// ReadFileLineByLine - Reads file line by line and calls delegate
func ReadFileLineByLine(path string, delegate delegateString) {
file, err := os.Open(path)
if err != nil {
panic(err)
}
CheckErr(err)
defer file.Close()
scanner := bufio.NewScanner(file)

16
utils/getHashtag.go Normal file
View File

@@ -0,0 +1,16 @@
package utils
import (
res "../resources"
"fmt"
"strings"
)
// GetHashtagFromURL - Get's tag name from passed url
func GetHashtagFromURL(str string) string {
if match := strings.Contains(str, "/tag/"); match {
return strings.Split(str, "/tag/")[1]
}
panic(fmt.Sprintf(res.ErrorCouldNotRecogniseURL, str))
}

28
utils/getUsername.go Normal file
View File

@@ -0,0 +1,28 @@
package utils
import (
config "../models/config"
res "../resources"
"fmt"
"regexp"
"strings"
)
// GetUsername - Get's username from passed URL param
func GetUsername() string {
return GetUsernameFromString(config.Config.URL)
}
// GetUsernameFromString - Get's username from passed param
func GetUsernameFromString(str string) string {
if match := strings.Contains(str, "/"); !match { // Not url
return strings.Replace(str, "@", "", -1)
}
if match, _ := regexp.MatchString(".+tiktok\\.com/@.+", str); match { // URL
stripedSuffix := strings.Split(str, "@")[1]
return strings.Split(stripedSuffix, "/")[0]
}
panic(fmt.Sprintf(res.ErrorCouldNotRecogniseURL, str))
}

View File

@@ -1,6 +1,7 @@
package models
package utils
import (
config "../models/config"
testUtil "../unitTestUtil"
"testing"
)
@@ -8,7 +9,7 @@ import (
func TestGetUsername(t *testing.T) {
testCaseDelegate := func(t *testing.T, url string, username string) {
tu := testUtil.TestUtil{T: t}
Config.URL = url
config.Config.URL = url
actual := GetUsername()
tu.AssertString(actual, username, "Username")
}

31
utils/log.go Normal file
View File

@@ -0,0 +1,31 @@
package utils
import (
config "../models/config"
"fmt"
"os"
)
// Log - Write to std out
func Log(a ...interface{}) {
if !config.Config.Quiet {
fmt.Println(a...)
}
}
// Logf - Write formated text
func Logf(format string, a ...interface{}) {
if !config.Config.Quiet {
fmt.Printf(format, a...)
}
}
// LogFatal - Write error and panic
func LogFatal(format string, a ...interface{}) {
panic(fmt.Sprintf(format, a...))
}
// LogErr - Write error
func LogErr(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
}

View File

@@ -2,14 +2,11 @@ package utils
import (
"io/ioutil"
"log"
)
// ReadFileAsString - Returns contents of given file
func ReadFileAsString(fileName string) string {
content, err := ioutil.ReadFile(fileName)
if err != nil {
log.Fatal(err)
}
CheckErr(err)
return string(content)
}

View File

@@ -1,8 +1,8 @@
package workflows
import (
res "../resources"
utils "../utils"
"fmt"
)
// CanUseDownloadBatchFile - Check's if DownloadBatchFile can be used
@@ -13,7 +13,7 @@ func CanUseDownloadBatchFile(batchFilePath string) bool {
// DownloadBatchFile - Download items from batch file
func DownloadBatchFile(batchFilePath string) {
if !utils.CheckIfExists(batchFilePath) {
panic(fmt.Sprintf("File path %s not found.", batchFilePath))
utils.LogFatal(res.ErrorPathNotFound, batchFilePath)
}
utils.ReadFileLineByLine(batchFilePath, downloadItem)

View File

@@ -0,0 +1,45 @@
package workflows
import (
client "../client"
config "../models/config"
res "../resources"
utils "../utils"
"fmt"
"strings"
)
// CanUseDownloadHashtag - Test's if this workflow can be used for parameter
func CanUseDownloadHashtag(url string) bool {
match := strings.Contains(url, "/tag/")
return match
}
// DownloadHashtag - Download videos marked with given hashtag
func DownloadHashtag(url string) {
uploads, err := client.GetHashtagUploads(url)
if err != nil {
utils.LogErr(res.ErrorCouldNotGetUserUploads, err.Error())
return
}
uploadCount := len(uploads)
hashtag := utils.GetHashtagFromURL(url)
downloadDir := fmt.Sprintf("%s/%s", config.Config.OutputPath, hashtag)
utils.InitOutputDirectory(downloadDir)
for index, upload := range uploads {
downloadVideo(upload, downloadDir)
utils.Logf("\r[%d/%d] Downloaded", index+1, uploadCount)
}
utils.Log()
}
func GetHashtagJson(url string) {
uploads, err := client.GetHashtagUploads(url)
if err != nil {
utils.LogErr(res.ErrorCouldNotGetUserUploads, err.Error())
return
}
fmt.Printf("%s", uploads)
}

View File

@@ -2,7 +2,8 @@ package workflows
import (
client "../client"
models "../models"
config "../models/config"
res "../resources"
utils "../utils"
"fmt"
"regexp"
@@ -16,13 +17,29 @@ func CanUseDownloadMusic(url string) bool {
// DownloadMusic - Download all videos by given music
func DownloadMusic(url string) {
uploads := client.GetMusicUploads(url)
uploads, err := client.GetMusicUploads(url)
if err != nil {
utils.LogErr(res.ErrorCouldNotGetUserUploads, err.Error())
return
}
uploadCount := len(uploads)
for _, upload := range uploads {
username := models.GetUsernameFromString(upload.Uploader)
downloadDir := fmt.Sprintf("%s/%s", models.Config.OutputPath, username)
for index, upload := range uploads {
username := utils.GetUsernameFromString(upload.Uploader)
downloadDir := fmt.Sprintf("%s/%s", config.Config.OutputPath, username)
utils.InitOutputDirectory(downloadDir)
downloadVideo(upload, downloadDir)
utils.Logf("\r[%d/%d] Downloaded", index+1, uploadCount)
}
utils.Log()
}
func GetMusicJson(url string) {
uploads, err := client.GetMusicUploadsJson(url)
if err != nil {
utils.LogErr(res.ErrorCouldNotGetUserUploads, err.Error())
return
}
fmt.Printf("%s", uploads)
}

View File

@@ -2,26 +2,45 @@ package workflows
import (
client "../client"
models "../models"
config "../models/config"
res "../resources"
utils "../utils"
"fmt"
"regexp"
"strings"
)
// CanUseDownloadUser - Test's if this workflow can be used for parameter
func CanUseDownloadUser(url string) bool {
match := strings.Contains(url, "/")
return !match
isURL := strings.Contains(url, "/")
match, _ := regexp.MatchString(".+com\\/@[^\\/]+", url)
return !isURL || match
}
// DownloadUser - Download all user's videos
func DownloadUser(username string) {
downloadDir := fmt.Sprintf("%s/%s", models.Config.OutputPath, username)
uploads := client.GetUserUploads(username)
uploads, err := client.GetUserUploads(username)
if err != nil {
utils.LogErr(res.ErrorCouldNotGetUserUploads, err.Error())
return
}
uploadCount := len(uploads)
downloadDir := fmt.Sprintf("%s/%s", config.Config.OutputPath, username)
utils.InitOutputDirectory(downloadDir)
for _, upload := range uploads {
for index, upload := range uploads {
downloadVideo(upload, downloadDir)
utils.Logf("\r[%d/%d] Downloaded", index+1, uploadCount)
}
utils.Log()
}
func GetUserVideosJson(username string) {
uploads, err := client.GetUserUploadsJson(username)
if err != nil {
utils.LogErr(res.ErrorCouldNotGetUserUploads, err.Error())
return
}
fmt.Printf("%s", uploads)
}

View File

@@ -3,6 +3,8 @@ package workflows
import (
client "../client"
models "../models"
config "../models/config"
res "../resources"
utils "../utils"
"fmt"
"regexp"
@@ -16,12 +18,17 @@ func CanUseDownloadSingleVideo(url string) bool {
// DownloadSingleVideo - Downloads single video
func DownloadSingleVideo(url string) {
username := models.GetUsernameFromString(url)
upload := client.GetVideoDetails(url)
downloadDir := fmt.Sprintf("%s/%s", models.Config.OutputPath, username)
username := utils.GetUsernameFromString(url)
upload, err := client.GetVideoDetails(url)
if err != nil {
utils.LogErr(res.ErrorCouldNotGetUserUploads, err.Error())
return
}
downloadDir := fmt.Sprintf("%s/%s", config.Config.OutputPath, username)
utils.InitOutputDirectory(downloadDir)
downloadVideo(upload, downloadDir)
utils.Log("[1/1] Downloaded\n")
}
// DownloadVideo - Downloads one video
@@ -30,14 +37,12 @@ func downloadVideo(upload models.Upload, downloadDir string) {
downloadPath := fmt.Sprintf("%s/%s.mp4", downloadDir, uploadID)
if utils.CheckIfExists(downloadPath) {
fmt.Println("Upload '" + uploadID + "' already downloaded, skipping")
return
}
fmt.Println("Downloading upload item '" + uploadID + "' to " + downloadPath)
utils.DownloadFile(downloadPath, upload.URL)
if models.Config.MetaData {
if config.Config.MetaData {
metadataPath := fmt.Sprintf("%s/%s.json", downloadDir, uploadID)
upload.WriteToFile(metadataPath)
}

View File

@@ -1,8 +1,9 @@
package workflows
import (
models "../models"
"fmt"
config "../models/config"
res "../resources"
utils "../utils"
)
// StartWorkflowByParameter - Start needed workflow by given parameter
@@ -10,7 +11,11 @@ func StartWorkflowByParameter(url string) {
// Music
if CanUseDownloadMusic(url) {
DownloadMusic(url)
if config.Config.JSONOnly {
GetMusicJson(url)
} else {
DownloadMusic(url)
}
return
}
@@ -22,9 +27,24 @@ func StartWorkflowByParameter(url string) {
// Tiktok user
if CanUseDownloadUser(url) {
DownloadUser(models.GetUsernameFromString(url))
if config.Config.JSONOnly {
GetUserVideosJson(utils.GetUsernameFromString(url))
} else {
DownloadUser(utils.GetUsernameFromString(url))
}
return
}
panic(fmt.Sprintf("Could not recognise URL format of string %s", url))
// Tiktok hashtag
if CanUseDownloadHashtag(url) {
if config.Config.JSONOnly {
GetHashtagJson(url)
} else {
DownloadHashtag(url)
}
return
}
utils.LogFatal(res.ErrorCouldNotRecogniseURL, url)
}