Skip to content

Commit

Permalink
refactor: using C++17 filesystem
Browse files Browse the repository at this point in the history
  • Loading branch information
moesnow committed Jul 16, 2023
1 parent 50eeef0 commit 86ee15f
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 51 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
CC = g++
CFLAGS = -Wall -Werror -std=c++11
CFLAGS = -Wall -Werror -std=c++17
LIBS = -lcurl

TARGET = bing-wallpaper-macos
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Automatically update Bing wallpapers on macOS, with support for multiple monitor

Bing wallpapers are downloaded to the `~/.local/bing-wallpaper-macos` directory.

The last update date is recorded in the `~/.config/bing-wallpaper-macos` directory.
The last update date is recorded in the `~/.local/bing-wallpaper-macos` directory.

When updating wallpapers, the old wallpaper files in the directory will be removed.

Expand Down
2 changes: 1 addition & 1 deletion README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

Bing 壁纸会被下载到 `~/.local/bing-wallpaper-macos` 目录内

并在 `~/.config/bing-wallpaper-macos` 目录内记录上次更新日期
并在 `~/.local/bing-wallpaper-macos` 目录内记录上次更新日期

更新壁纸时会先删除目录内的旧壁纸文件

Expand Down
93 changes: 45 additions & 48 deletions bing-wallpaper-macos.cpp
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
#include <curl/curl.h>

#include <filesystem>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>

using namespace std;
using namespace std::filesystem;
using json = nlohmann::json;

// Function declarations
void printHelp();
void printVersion();
void printUnknown(const string& arg);
string getYesterdayDate();
bool check_run_today(const string& configPath);
bool checkRunToday(const path& configpath);
bool checkNetworkConnection(const string& url);
string getJsonContent(const string& url);
string replaceAndAddPrefix(const string& url, const string& target, const string& replacement, const string& prefix);
string getTemporaryFilePath();
void clearDirectory(const string& path);
string downloadFile(const string& url, const string& filedir, const string& filename);
bool runCommand(const string& script);
void updateConfig(const string& configDir, const string& configName);
void clearDirectory(const path& filepath);
bool downloadFile(const string& url, const path& filepath);
bool runShellCommand(const string& script);
void updateConfig(const path& configpath);

// Constants
const string ProgramName = "bing-wallpaper-macos";
const string ProgramVersion = "0.0.4";
const string ConfigDir = string(getenv("HOME")) + "/.config/" + ProgramName + "/";
const string DownloadDir = string(getenv("HOME")) + "/.local/" + ProgramName + "/";
const string ProgramVersion = "0.0.5";
const path ProgramDir = string(getenv("HOME")) + "/.local/" + ProgramName + "/";
const string ConfigName = "config.json";
const string CheckNetworkUrl = "https://cn.bing.com";
const string WallpaperJsonUrl = CheckNetworkUrl + "/HPImageArchive.aspx?format=js&n=1&idx=0";
Expand All @@ -43,7 +43,7 @@ int main(int argc, char* argv[]) {
if (argc > 1) {
string arg(argv[1]);
if (arg == "--auto") {
if (check_run_today(ConfigDir + ConfigName)) {
if (checkRunToday(ProgramDir / ConfigName)) {
return 0;
}
} else if (arg == "--help") {
Expand All @@ -68,24 +68,24 @@ int main(int argc, char* argv[]) {
string wallpaperUrl = wallpaperjsonData["images"][0]["url"];
string modifiedUrl = replaceAndAddPrefix(wallpaperUrl, "1920x1080", "UHD", "https://cn.bing.com");
string fileName = (string)wallpaperjsonData["images"][0]["startdate"] + "_" + (string)wallpaperjsonData["images"][0]["title"] + ".jpg";
string downloadedFilePath = downloadFile(modifiedUrl, DownloadDir, fileName);
if (downloadedFilePath.empty()) {
path downloadedFilePath = ProgramDir / fileName;
if (downloadFile(modifiedUrl, downloadedFilePath)) {
cerr << "Failed to download wallpaper" << endl;
return 1;
}

string appleScript1 = "tell application \"System Events\" to tell every desktop to set picture to \"" + downloadedFilePath + "\"";
string appleScript2 = "tell application \"System Events\" to if picture of item 1 of desktops does not contain \"" + downloadedFilePath + "\" then error";
string appleScript1 = "tell application \"System Events\" to tell every desktop to set picture to \"" + downloadedFilePath.string() + "\"";
string appleScript2 = "tell application \"System Events\" to if picture of item 1 of desktops does not contain \"" + downloadedFilePath.string() + "\" then error";
string shellCommand = "osascript -e '" + appleScript1 + "' -e '" + appleScript2 + "'";
if (runCommand(shellCommand)) {
if (runShellCommand(shellCommand)) {
cout << "\033[0m[\033[33m" << getYesterdayDate() << "\033[0m] "
<< "\033[35mWallpaper applied successfully :)" << endl;
} else {
cerr << "Failed to apply wallpaper" << endl;
return 1;
}

updateConfig(ConfigDir, ConfigName);
updateConfig(ProgramDir / ConfigName);

return 0;
}
Expand Down Expand Up @@ -122,16 +122,20 @@ string getYesterdayDate() {
return string(buffer);
}

bool check_run_today(const string& configPath) {
bool checkRunToday(const path& configPath) {
ifstream configFile(configPath);
if (configFile.is_open()) {
json configJson;
configFile >> configJson;
if (configJson.contains("last_update_date")) {
if (getYesterdayDate() == configJson["last_update_date"]) {
configFile.close();
return true;
try {
json configJson;
configFile >> configJson;
if (configJson.contains("last_update_date")) {
if (getYesterdayDate() == configJson["last_update_date"]) {
configFile.close();
return true;
}
}
} catch (const exception& e) {
cerr << "Error: Failed to parse config file. " << e.what() << endl;
}
}
configFile.close();
Expand Down Expand Up @@ -173,7 +177,6 @@ string getJsonContent(const string& url) {
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);

Expand Down Expand Up @@ -203,24 +206,22 @@ string replaceAndAddPrefix(const string& url, const string& target, const string
return prefix + modifiedUrl;
}

void clearDirectory(const string& path) {
string command = "rm -rf \"" + path + "\"/*.jpg";
int status = system(command.c_str());
if (status != 0) {
cerr << "Failed to clear directory: " << path << endl;
void clearDirectory(const path& filepath) {
for (const auto& entry : directory_iterator(filepath)) {
if (entry.is_regular_file() && entry.path().extension() == ".jpg") {
remove(entry);
}
}
}

string downloadFile(const string& url, const string& filedir, const string& filename) {
string createDirCommand = "mkdir -p " + filedir;
system(createDirCommand.c_str());
string FilePath = filedir + filename;
ifstream file(FilePath);
bool downloadFile(const string& url, const path& filepath) {
create_directories(filepath.parent_path());
ifstream file(filepath);
if (file.good()) {
// cout << "file exists, skip download" << endl;
return FilePath;
return false;
} else {
clearDirectory(filedir);
clearDirectory(filepath);
}

CURL* curl = curl_easy_init();
Expand All @@ -233,37 +234,33 @@ string downloadFile(const string& url, const string& filedir, const string& file

CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
ofstream outputFile(FilePath, ios::binary);
ofstream outputFile(filepath, ios::binary);
outputFile.write(buffer.c_str(), buffer.size());
outputFile.close();
} else {
FilePath.clear();
cerr << "Failed to download file: " << curl_easy_strerror(res) << endl;
return true;
}

curl_easy_cleanup(curl);
} else {
FilePath.clear();
cerr << "Failed to initialize libcurl" << endl;
return true;
}

return FilePath;
return false;
}

bool runCommand(const string& command) {
bool runShellCommand(const string& command) {
int result = system(command.c_str());
return !result;
}

void updateConfig(const string& configDir, const string& configName) {
string createDirCommand = "mkdir -p " + configDir;
system(createDirCommand.c_str());

void updateConfig(const path& configPath) {
create_directories(configPath.parent_path());
json jsonData;
jsonData["last_update_date"] = getYesterdayDate();

string filePath = configDir + configName;
ofstream file(filePath);
ofstream file(configPath);
if (file.is_open()) {
file << jsonData.dump(4);
file.close();
Expand Down

0 comments on commit 86ee15f

Please sign in to comment.