Skip to main content

Organizing your dropbox Camera Upload folder with Go

·349 words·2 mins

A few years ago I wrote a small Python script to organize the photos uploaded from your phone to Dropbox. Lately, I have been rewriting some of my python scripts to golang for practice and also performance.

All photos are uploaded to Dropbox with a name pattern like 2018-08-01 05.56.40.jpg. What all it does is to parse the date and move it to the right place, for example, 2018-08-01 will move it to a folder called 08-August inside 2018.

golang dropbox photo organizer

Source code:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

func main() {

	// Start timer to calculate time to execute all functions
	start := time.Now()

	// Accepted file format array
	fileFormats := []string{".JPG", ".jpg", ".MOV", ".mov", ".PNG", ".png", ".mp4", ".MP4"}

	// List all files in directory
	files := listFilesInDirectory(".")

	for _, f := range files {
		fileExtension := filepath.Ext(f.Name())

		// Only work with file extensions from fileFormats
		if stringInSlice(fileExtension, fileFormats) {

			go moveFile(f.Name(), parseDate(f.Name()))

		}
	}

	elapsed := time.Since(start)
	fmt.Println("Job completed in", elapsed)

	fmt.Println("Press ENTER to quit application/")

	var input string
	fmt.Scanln(&input)
}

func stringInSlice(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}

func parseDate(a string) []string {
	fileDates := strings.Split(strings.Split(a, " ")[0], "-")
	return fileDates
}

func createDirIfNotExist(dir string) {
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err = os.MkdirAll(dir, 0755)
		if err != nil {
			log.Fatal(err)
		}
	}
}

func listFilesInDirectory(dir string) []os.FileInfo {
	files, err := ioutil.ReadDir(dir)

	// In case of error, print the error message
	if err != nil {
		log.Fatal(err)
	}
	return files
}

func moveFile(filename string, parsedDate []string) {
	// Months of the year
	monthsOfTheYear := [12]string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}

	year := parsedDate[0]
	month := parsedDate[1]
	monthInt, _ := strconv.ParseInt(parsedDate[1], 10, 64)

	// Create directory to move file
	createDirIfNotExist(filepath.Join(year, month+"-"+monthsOfTheYear[monthInt-1]))

	// Move file
	os.Rename(filename, filepath.Join(year, month+"-"+monthsOfTheYear[monthInt-1], filename))
}

You can also download the compiled file below, just make sure you make it executable with

chmod +x organize_photos

and run it with

./organize_photos

Download link.