2018-04-27 15:14:23 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2018-05-25 04:03:54 +02:00
|
|
|
url2 "net/url"
|
2018-04-27 15:14:23 +02:00
|
|
|
"os"
|
2018-05-17 02:08:52 +02:00
|
|
|
|
2018-05-25 04:03:54 +02:00
|
|
|
"os/user"
|
2018-05-24 02:32:11 +02:00
|
|
|
|
2018-05-26 02:43:16 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"strconv"
|
|
|
|
|
2018-05-17 01:42:06 +02:00
|
|
|
"github.com/lbryio/lbry.go/errors"
|
2018-04-27 15:14:23 +02:00
|
|
|
"github.com/lbryio/lbry.go/null"
|
|
|
|
"github.com/lbryio/lbry.go/util"
|
2018-05-17 01:42:06 +02:00
|
|
|
sync "github.com/lbryio/lbry.go/ytsync"
|
2018-04-27 15:14:23 +02:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
2018-05-26 02:43:16 +02:00
|
|
|
var APIURL string
|
|
|
|
var APIToken string
|
|
|
|
|
2018-04-27 15:14:23 +02:00
|
|
|
func init() {
|
|
|
|
var selfSyncCmd = &cobra.Command{
|
2018-06-06 14:37:57 +02:00
|
|
|
Use: "selfsync <youtube_api_key>",
|
|
|
|
Args: cobra.RangeArgs(1, 1),
|
2018-04-27 15:14:23 +02:00
|
|
|
Short: "Publish youtube channels into LBRY network automatically.",
|
|
|
|
Run: selfSync,
|
|
|
|
}
|
|
|
|
selfSyncCmd.Flags().BoolVar(&stopOnError, "stop-on-error", false, "If a publish fails, stop all publishing and exit")
|
|
|
|
selfSyncCmd.Flags().IntVar(&maxTries, "max-tries", defaultMaxTries, "Number of times to try a publish that fails")
|
|
|
|
selfSyncCmd.Flags().BoolVar(&takeOverExistingChannel, "takeover-existing-channel", false, "If channel exists and we don't own it, take over the channel")
|
|
|
|
selfSyncCmd.Flags().IntVar(&limit, "limit", 0, "limit the amount of channels to sync")
|
2018-05-17 01:42:06 +02:00
|
|
|
selfSyncCmd.Flags().BoolVar(&skipSpaceCheck, "skip-space-check", false, "Do not perform free space check on startup")
|
2018-05-24 02:32:11 +02:00
|
|
|
selfSyncCmd.Flags().BoolVar(&syncUpdate, "update", false, "Update previously synced channels instead of syncing new ones (short for --status synced)")
|
2018-05-25 04:03:54 +02:00
|
|
|
selfSyncCmd.Flags().StringVar(&syncStatus, "status", StatusQueued, "Specify which queue to pull from. Overrides --update (Default: queued)")
|
2018-06-06 14:37:57 +02:00
|
|
|
selfSyncCmd.Flags().Int64Var(&syncFrom, "after", time.Unix(0, 0).Unix(), "Specify from when to pull jobs [Unix time](Default: 0)")
|
|
|
|
selfSyncCmd.Flags().Int64Var(&syncUntil, "before", time.Now().Unix(), "Specify until when to pull jobs [Unix time](Default: current Unix time)")
|
2018-06-06 23:47:28 +02:00
|
|
|
selfSyncCmd.Flags().IntVar(&concurrentJobs, "concurrent-jobs", 1, "how many jobs to process concurrently (Default: 1)")
|
2018-05-17 01:42:06 +02:00
|
|
|
|
2018-04-27 15:14:23 +02:00
|
|
|
RootCmd.AddCommand(selfSyncCmd)
|
2018-05-26 02:43:16 +02:00
|
|
|
APIURL = os.Getenv("LBRY_API")
|
|
|
|
APIToken = os.Getenv("LBRY_API_TOKEN")
|
|
|
|
if APIURL == "" {
|
|
|
|
log.Errorln("An API URL was not defined. Please set the environment variable LBRY_API")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if APIToken == "" {
|
|
|
|
log.Errorln("An API Token was not defined. Please set the environment variable LBRY_API_TOKEN")
|
|
|
|
return
|
|
|
|
}
|
2018-04-27 15:14:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type APIJobsResponse struct {
|
|
|
|
Success bool `json:"success"`
|
|
|
|
Error null.String `json:"error"`
|
|
|
|
Data []APIYoutubeChannel `json:"data"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type APIYoutubeChannel struct {
|
|
|
|
ChannelId string `json:"channel_id"`
|
|
|
|
TotalVideos uint `json:"total_videos"`
|
|
|
|
DesiredChannelName string `json:"desired_channel_name"`
|
|
|
|
SyncServer null.String `json:"sync_server"`
|
|
|
|
}
|
|
|
|
|
2018-05-26 02:43:16 +02:00
|
|
|
func fetchChannels(status string) ([]APIYoutubeChannel, error) {
|
2018-06-09 01:14:55 +02:00
|
|
|
host, err := os.Hostname()
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Err("could not detect system hostname")
|
|
|
|
}
|
2018-05-26 02:43:16 +02:00
|
|
|
url := APIURL + "/yt/jobs"
|
2018-05-24 02:32:11 +02:00
|
|
|
res, _ := http.PostForm(url, url2.Values{
|
2018-05-26 02:43:16 +02:00
|
|
|
"auth_token": {APIToken},
|
2018-05-24 02:32:11 +02:00
|
|
|
"sync_status": {status},
|
2018-06-04 16:35:35 +02:00
|
|
|
"min_videos": {strconv.Itoa(1)},
|
2018-06-06 14:37:57 +02:00
|
|
|
"after": {strconv.Itoa(int(syncFrom))},
|
|
|
|
"before": {strconv.Itoa(int(syncUntil))},
|
2018-06-09 01:14:55 +02:00
|
|
|
"sync_server": {host},
|
2018-05-24 02:32:11 +02:00
|
|
|
})
|
2018-04-27 15:14:23 +02:00
|
|
|
defer res.Body.Close()
|
|
|
|
body, _ := ioutil.ReadAll(res.Body)
|
|
|
|
var response APIJobsResponse
|
2018-06-09 01:14:55 +02:00
|
|
|
err = json.Unmarshal(body, &response)
|
2018-04-27 15:14:23 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-05-26 02:43:16 +02:00
|
|
|
if response.Data == nil {
|
|
|
|
return nil, errors.Err(response.Error)
|
|
|
|
}
|
2018-06-04 16:35:35 +02:00
|
|
|
log.Printf("Fetched channels: %d", len(response.Data))
|
2018-04-27 15:14:23 +02:00
|
|
|
return response.Data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type APISyncUpdateResponse struct {
|
|
|
|
Success bool `json:"success"`
|
|
|
|
Error null.String `json:"error"`
|
|
|
|
Data null.String `json:"data"`
|
|
|
|
}
|
|
|
|
|
2018-05-26 02:43:16 +02:00
|
|
|
func setChannelSyncStatus(channelID string, status string) error {
|
2018-04-27 15:14:23 +02:00
|
|
|
host, err := os.Hostname()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Err("could not detect system hostname")
|
|
|
|
}
|
2018-05-26 02:43:16 +02:00
|
|
|
url := APIURL + "/yt/sync_update"
|
2018-05-24 02:32:11 +02:00
|
|
|
|
|
|
|
res, _ := http.PostForm(url, url2.Values{
|
|
|
|
"channel_id": {channelID},
|
|
|
|
"sync_server": {host},
|
2018-05-26 02:43:16 +02:00
|
|
|
"auth_token": {APIToken},
|
2018-05-24 02:32:11 +02:00
|
|
|
"sync_status": {status},
|
|
|
|
})
|
2018-04-27 15:14:23 +02:00
|
|
|
defer res.Body.Close()
|
|
|
|
body, _ := ioutil.ReadAll(res.Body)
|
|
|
|
var response APISyncUpdateResponse
|
|
|
|
err = json.Unmarshal(body, &response)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !response.Error.IsNull() {
|
|
|
|
return errors.Err(response.Error.String)
|
|
|
|
}
|
|
|
|
if !response.Data.IsNull() && response.Data.String == "ok" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return errors.Err("invalid API response")
|
|
|
|
}
|
|
|
|
|
2018-05-25 04:03:54 +02:00
|
|
|
func spaceCheck() error {
|
2018-05-17 01:42:06 +02:00
|
|
|
usr, err := user.Current()
|
|
|
|
if err != nil {
|
2018-05-25 04:03:54 +02:00
|
|
|
return err
|
2018-05-17 01:42:06 +02:00
|
|
|
}
|
|
|
|
usedPctile, err := util.GetUsedSpace(usr.HomeDir + "/.lbrynet/blobfiles/")
|
|
|
|
if err != nil {
|
2018-05-25 04:03:54 +02:00
|
|
|
return err
|
2018-05-17 01:42:06 +02:00
|
|
|
}
|
2018-06-06 14:37:57 +02:00
|
|
|
if usedPctile >= 0.90 && !skipSpaceCheck {
|
2018-06-06 23:47:28 +02:00
|
|
|
return errors.Err(fmt.Sprintf("more than 90%% of the space has been used. use --skip-space-check to ignore. Used: %.1f%%", usedPctile*100))
|
2018-05-17 01:42:06 +02:00
|
|
|
}
|
2018-05-17 02:08:52 +02:00
|
|
|
util.SendToSlackInfo("disk usage: %.1f%%", usedPctile*100)
|
2018-05-25 04:03:54 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func selfSync(cmd *cobra.Command, args []string) {
|
|
|
|
slackToken := os.Getenv("SLACK_TOKEN")
|
|
|
|
if slackToken == "" {
|
|
|
|
log.Error("A slack token was not present in env vars! Slack messages disabled!")
|
|
|
|
} else {
|
|
|
|
util.InitSlack(os.Getenv("SLACK_TOKEN"))
|
|
|
|
}
|
2018-05-26 02:43:16 +02:00
|
|
|
err := spaceCheck()
|
|
|
|
if err != nil {
|
|
|
|
util.SendToSlackError(err.Error())
|
|
|
|
return
|
|
|
|
}
|
2018-04-27 15:14:23 +02:00
|
|
|
ytAPIKey := args[0]
|
2018-05-26 02:43:16 +02:00
|
|
|
//authToken := args[1]
|
2018-04-27 15:14:23 +02:00
|
|
|
|
2018-05-24 02:32:11 +02:00
|
|
|
if !util.InSlice(syncStatus, SyncStatuses) {
|
|
|
|
log.Errorf("status must be one of the following: %v\n", SyncStatuses)
|
|
|
|
return
|
|
|
|
}
|
2018-05-26 02:43:16 +02:00
|
|
|
|
2018-04-27 15:14:23 +02:00
|
|
|
if stopOnError && maxTries != defaultMaxTries {
|
|
|
|
log.Errorln("--stop-on-error and --max-tries are mutually exclusive")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if maxTries < 1 {
|
|
|
|
log.Errorln("setting --max-tries less than 1 doesn't make sense")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if limit < 0 {
|
|
|
|
log.Errorln("setting --limit less than 0 (unlimited) doesn't make sense")
|
|
|
|
return
|
|
|
|
}
|
2018-05-25 04:03:54 +02:00
|
|
|
syncCount := 0
|
|
|
|
if syncStatus == StatusQueued {
|
2018-05-25 19:57:03 +02:00
|
|
|
mainLoop:
|
2018-05-25 04:03:54 +02:00
|
|
|
for {
|
|
|
|
//before processing the queued ones first clear the pending ones (if any)
|
|
|
|
//TODO: extract method
|
2018-05-25 19:57:03 +02:00
|
|
|
queuesToSync := []string{
|
|
|
|
StatusSyncing,
|
2018-05-25 04:03:54 +02:00
|
|
|
}
|
|
|
|
if syncUpdate {
|
2018-05-25 19:57:03 +02:00
|
|
|
queuesToSync = append(queuesToSync, StatusSynced)
|
2018-06-11 22:06:59 +02:00
|
|
|
} else {
|
|
|
|
queuesToSync = append(queuesToSync, StatusQueued)
|
2018-05-25 19:57:03 +02:00
|
|
|
}
|
|
|
|
for _, v := range queuesToSync {
|
2018-05-26 02:43:16 +02:00
|
|
|
interruptedByUser, err := processQueue(v, ytAPIKey, &syncCount)
|
2018-05-25 04:03:54 +02:00
|
|
|
if err != nil {
|
2018-05-25 19:57:03 +02:00
|
|
|
util.SendToSlackError(err.Error())
|
|
|
|
break mainLoop
|
2018-05-25 04:03:54 +02:00
|
|
|
}
|
|
|
|
if interruptedByUser {
|
2018-05-26 02:43:16 +02:00
|
|
|
util.SendToSlackInfo("interrupted by user!")
|
2018-05-25 19:57:03 +02:00
|
|
|
break mainLoop
|
2018-05-25 04:03:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// sync whatever was specified
|
2018-05-26 02:43:16 +02:00
|
|
|
_, err := processQueue(syncStatus, ytAPIKey, &syncCount)
|
2018-05-25 04:03:54 +02:00
|
|
|
if err != nil {
|
2018-05-25 19:57:03 +02:00
|
|
|
util.SendToSlackError(err.Error())
|
2018-05-25 04:03:54 +02:00
|
|
|
return
|
|
|
|
}
|
2018-04-27 15:14:23 +02:00
|
|
|
}
|
2018-05-25 04:03:54 +02:00
|
|
|
util.SendToSlackInfo("Syncing process terminated!")
|
|
|
|
}
|
|
|
|
|
2018-05-26 02:43:16 +02:00
|
|
|
func processQueue(queueStatus string, ytAPIKey string, syncCount *int) (bool, error) {
|
|
|
|
util.SendToSlackInfo("Syncing %s channels", queueStatus)
|
|
|
|
channelsToSync, err := fetchChannels(queueStatus)
|
2018-05-25 19:57:03 +02:00
|
|
|
if err != nil {
|
|
|
|
return false, errors.Prefix("failed to fetch channels", err)
|
|
|
|
}
|
2018-06-04 16:35:35 +02:00
|
|
|
filteredChannelsToSync := make([]APIYoutubeChannel, len(channelsToSync))
|
|
|
|
host, err := os.Hostname()
|
|
|
|
if err != nil {
|
|
|
|
return false, errors.Err("could not detect system hostname")
|
|
|
|
}
|
|
|
|
index := 0
|
|
|
|
for _, v := range channelsToSync {
|
|
|
|
if !v.SyncServer.IsNull() && v.SyncServer.String != host {
|
|
|
|
filteredChannelsToSync[index] = v
|
|
|
|
index++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
interrupted, err := syncChannels(channelsToSync, ytAPIKey, syncCount)
|
2018-05-25 19:57:03 +02:00
|
|
|
util.SendToSlackInfo("Finished syncing %s channels", queueStatus)
|
2018-06-04 16:35:35 +02:00
|
|
|
return interrupted, err
|
2018-05-25 19:57:03 +02:00
|
|
|
}
|
|
|
|
|
2018-05-25 04:03:54 +02:00
|
|
|
// syncChannels processes a slice of youtube channels (channelsToSync) and returns a bool that indicates whether
|
|
|
|
// the execution finished by itself or was interrupted by the user and an error if anything happened
|
2018-05-26 02:43:16 +02:00
|
|
|
func syncChannels(channelsToSync []APIYoutubeChannel, ytAPIKey string, syncCount *int) (bool, error) {
|
2018-05-05 13:22:33 +02:00
|
|
|
host, err := os.Hostname()
|
|
|
|
if err != nil {
|
|
|
|
host = ""
|
|
|
|
}
|
2018-06-04 16:35:35 +02:00
|
|
|
for loop := 0; loop < len(channelsToSync) && (limit == 0 || *syncCount < limit); loop++ {
|
|
|
|
//log.Printf("inside loop: %d", loop)
|
2018-05-25 04:03:54 +02:00
|
|
|
err = spaceCheck()
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
2018-04-27 15:14:23 +02:00
|
|
|
//avoid dereferencing
|
2018-06-04 16:35:35 +02:00
|
|
|
channel := channelsToSync[loop]
|
2018-04-27 15:14:23 +02:00
|
|
|
channelID := channel.ChannelId
|
|
|
|
lbryChannelName := channel.DesiredChannelName
|
|
|
|
if channel.TotalVideos < 1 {
|
2018-05-24 02:32:11 +02:00
|
|
|
util.SendToSlackInfo("Channel %s has no videos. Skipping", lbryChannelName)
|
2018-04-27 15:14:23 +02:00
|
|
|
continue
|
|
|
|
}
|
2018-05-05 13:22:33 +02:00
|
|
|
if !channel.SyncServer.IsNull() && channel.SyncServer.String != host {
|
2018-05-24 02:32:11 +02:00
|
|
|
util.SendToSlackInfo("Channel %s is being synced by another server: %s", lbryChannelName, channel.SyncServer.String)
|
2018-04-27 15:14:23 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
//acquire the lock on the channel
|
2018-05-26 02:43:16 +02:00
|
|
|
err := setChannelSyncStatus(channelID, StatusSyncing)
|
2018-04-27 15:14:23 +02:00
|
|
|
if err != nil {
|
2018-06-11 22:06:59 +02:00
|
|
|
//util.SendToSlackError("Failed acquiring sync rights for channel %s: %v", lbryChannelName, err)
|
2018-04-27 15:14:23 +02:00
|
|
|
continue
|
|
|
|
}
|
2018-06-04 16:35:35 +02:00
|
|
|
//increment only if successfully acquired lock
|
|
|
|
*syncCount++
|
2018-05-25 04:03:54 +02:00
|
|
|
util.SendToSlackInfo("Syncing %s to LBRY! (iteration %d)", lbryChannelName, *syncCount)
|
2018-04-27 15:14:23 +02:00
|
|
|
|
|
|
|
s := sync.Sync{
|
|
|
|
YoutubeAPIKey: ytAPIKey,
|
|
|
|
YoutubeChannelID: channelID,
|
|
|
|
LbryChannelName: lbryChannelName,
|
|
|
|
StopOnError: stopOnError,
|
|
|
|
MaxTries: maxTries,
|
2018-06-06 23:47:28 +02:00
|
|
|
ConcurrentVideos: concurrentJobs,
|
2018-04-27 15:14:23 +02:00
|
|
|
TakeOverExistingChannel: takeOverExistingChannel,
|
|
|
|
Refill: refill,
|
|
|
|
}
|
|
|
|
|
|
|
|
err = s.FullCycle()
|
2018-05-05 13:22:33 +02:00
|
|
|
util.SendToSlackInfo("Syncing " + lbryChannelName + " reached an end.")
|
2018-04-27 15:14:23 +02:00
|
|
|
if err != nil {
|
2018-05-05 13:22:33 +02:00
|
|
|
util.SendToSlackError(errors.FullTrace(err))
|
2018-05-17 01:42:06 +02:00
|
|
|
fatalErrors := []string{
|
|
|
|
"default_wallet already exists",
|
|
|
|
"WALLET HAS NOT BEEN MOVED TO THE WALLET BACKUP DIR",
|
|
|
|
}
|
|
|
|
if util.InSliceContains(err.Error(), fatalErrors) {
|
2018-05-25 04:03:54 +02:00
|
|
|
return s.IsInterrupted(), errors.Prefix("@Nikooo777 this requires manual intervention! Exiting...", err)
|
2018-05-17 01:42:06 +02:00
|
|
|
}
|
2018-04-27 15:48:34 +02:00
|
|
|
//mark video as failed
|
2018-05-26 02:43:16 +02:00
|
|
|
err := setChannelSyncStatus(channelID, StatusFailed)
|
2018-04-27 15:48:34 +02:00
|
|
|
if err != nil {
|
2018-05-25 04:03:54 +02:00
|
|
|
msg := fmt.Sprintf("Failed setting failed state for channel %s. \n@Nikooo777 this requires manual intervention! Exiting...", lbryChannelName)
|
|
|
|
return s.IsInterrupted(), errors.Prefix(msg, err)
|
2018-04-27 15:48:34 +02:00
|
|
|
}
|
2018-05-17 01:42:06 +02:00
|
|
|
continue
|
2018-04-27 15:14:23 +02:00
|
|
|
}
|
2018-05-24 02:32:11 +02:00
|
|
|
if s.IsInterrupted() {
|
2018-05-25 04:03:54 +02:00
|
|
|
return true, nil
|
2018-05-24 02:32:11 +02:00
|
|
|
}
|
2018-04-27 15:48:34 +02:00
|
|
|
//mark video as synced
|
2018-05-26 02:43:16 +02:00
|
|
|
err = setChannelSyncStatus(channelID, StatusSynced)
|
2018-04-27 15:48:34 +02:00
|
|
|
if err != nil {
|
2018-05-25 04:03:54 +02:00
|
|
|
msg := fmt.Sprintf("Failed setting failed state for channel %s. \n@Nikooo777 this requires manual intervention! Exiting...", lbryChannelName)
|
|
|
|
return false, errors.Prefix(msg, err)
|
2018-04-27 15:48:34 +02:00
|
|
|
}
|
2018-04-27 15:14:23 +02:00
|
|
|
}
|
2018-06-04 16:35:35 +02:00
|
|
|
if limit != 0 && *syncCount >= limit {
|
|
|
|
return true, nil
|
|
|
|
}
|
2018-05-25 04:03:54 +02:00
|
|
|
return false, nil
|
2018-04-27 15:14:23 +02:00
|
|
|
}
|