diff --git a/doc/examples/reddit_test.cpp b/doc/examples/reddit_test.cpp
new file mode 100644
index 0000000..6219947
--- /dev/null
+++ b/doc/examples/reddit_test.cpp
@@ -0,0 +1,452 @@
+/**
+ This file is a part of rexy's matrix bot
+ Copyright (C) 2019 rexy712
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+*/
+
+#include
+#include
+#include //move
+#include
+#include
+
+#include "common.hpp"
+
+#if defined(DEBUG_LEVEL) && DEBUG_LEVEL >= DBG_LEVEL_VERBOSE
+# define LIBAV_SET_LOG_LEVEL() av_log_set_level(AV_LOG_INFO)
+#else
+# define LIBAV_SET_LOG_LEVEL() av_log_set_level(AV_LOG_FATAL)
+#endif
+
+#include "raii/curler.hpp"
+#include "raii/filerd.hpp"
+#include "raii/rjp_string.hpp"
+#include "raii/string.hpp"
+#include "raii/rjp_ptr.hpp"
+#include "raii/static_string.hpp"
+#include "reddit.hpp"
+#include "matrix.hpp"
+
+extern "C"{
+# include //sws_scale
+# include //av_image_alloc
+}
+#include "libav/packet.hpp"
+#include "libav/fmt/context.hpp"
+
+bool find_avformat_stream(AVFormatContext* output_context, const AVFormatContext* input_context, int* input_index, int* output_index, int codec_type){
+ for(size_t i = 0;i < input_context->nb_streams;++i){
+ if(input_context->streams[i]->codecpar->codec_type == codec_type){
+ (*input_index) = i;
+
+ AVStream* in_stream = input_context->streams[i];
+ AVStream* out_stream = avformat_new_stream(output_context, NULL);
+ (*output_index) = out_stream->index;
+ avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
+ out_stream->codecpar->codec_tag = 0;
+
+ return true;
+ }
+ }
+ return false;
+}
+bool find_audio_stream(AVFormatContext* output_context, const AVFormatContext* audio_context, int* audio_in_stream, int* audio_out_stream){
+ return find_avformat_stream(output_context, audio_context, audio_in_stream, audio_out_stream, AVMEDIA_TYPE_AUDIO);
+}
+bool find_video_stream(AVFormatContext* output_context, const AVFormatContext* video_context, int* video_in_stream, int* video_out_stream){
+ return find_avformat_stream(output_context, video_context, video_in_stream, video_out_stream, AVMEDIA_TYPE_VIDEO);
+}
+
+bool get_frame(AVFormatContext* ctx, int ctx_index, AVPacket* pkt){
+ if(av_read_frame(ctx, pkt) >= 0){
+ do{
+ if(pkt->stream_index == ctx_index){
+ return true;
+ }
+ av_packet_unref(pkt);
+ }while(av_read_frame(ctx, pkt) >= 0);
+ }
+ return false;
+}
+int64_t correct_dts(AVFormatContext* output_context, AVPacket* packet, int64_t last_dts){
+ if(packet->dts < (last_dts + !(output_context->oformat->flags & AVFMT_TS_NONSTRICT)) && packet->dts != AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE){
+ int64_t next_dts = last_dts+1;
+ if(packet->pts >= packet->dts){
+ packet->pts = FFMAX(packet->pts, next_dts);
+ }
+ if(packet->pts == AV_NOPTS_VALUE){
+ packet->pts = next_dts;
+ }
+ packet->dts = next_dts;
+ }
+ return packet->dts;
+}
+//a lot copied from a github repo, but with all deprecation warnings fixed.
+//no idea how the one guy managed to figure out all this with the minimal and conflicting documentation for ffmpeg and libav
+//with the new code that fixes invalid input pts/dts, now the output framerate/bitrate is off
+bool mux_audio_video(const raii::string_base& audio_file, const raii::string_base& video_file, const raii::string_base& output_file){
+ REGISTER_LIBAV();
+ LIBAV_SET_LOG_LEVEL();
+
+ libavfmt::input_context audio_context(audio_file);
+ libavfmt::input_context video_context(video_file);
+ libavfmt::output_context output_context(output_file, "mp4");
+ int video_index_in = -1, audio_index_in = -1;
+ int video_index_out = -1, audio_index_out = -1;
+
+ if(!find_audio_stream(output_context, audio_context, &audio_index_in, &audio_index_out) ||
+ !find_video_stream(output_context, video_context, &video_index_in, &video_index_out))
+ {
+ fprintf(stderr, "Unable to find input stream in\n");
+ return false;
+ }
+
+ if(avformat_write_header(output_context, NULL) < 0){
+ return false;
+ }
+
+ int64_t video_pts = 0, audio_pts = 0;
+
+ //took me 2 days to realize I had to initialize these to the smallest possible int64 value instead of just 0
+ int64_t last_video_dts, last_audio_dts;
+ last_video_dts = last_audio_dts = AV_NOPTS_VALUE;
+
+ while(true){
+ libav::packet packet;
+ int64_t* last_dts;
+ AVFormatContext* in_context;
+ int stream_index = 0;
+ AVStream* in_stream, *out_stream;
+
+ //Read in a frame from the next stream
+ if(av_compare_ts(video_pts, video_context->streams[video_index_in]->time_base,
+ audio_pts, audio_context->streams[audio_index_in]->time_base) <= 0)
+ {
+ //video
+ last_dts = &last_video_dts;
+ in_context = video_context;
+ stream_index = video_index_out;
+
+ if(!get_frame(video_context, video_index_in, packet)){
+ break;
+ }
+ video_pts = packet->pts;
+ }else{
+ //audio
+ last_dts = &last_audio_dts;
+ in_context = audio_context;
+ stream_index = audio_index_out;
+
+ if(!get_frame(audio_context, audio_index_in, packet)){
+ break;
+ }
+ audio_pts = packet->pts;
+ }
+ in_stream = in_context->streams[packet->stream_index];
+ out_stream = output_context->streams[stream_index];
+
+ av_packet_rescale_ts(packet, in_stream->time_base, out_stream->time_base);
+
+ (*last_dts) = correct_dts(output_context, packet, *last_dts);
+
+ packet->pos = -1;
+ packet->stream_index = stream_index;
+
+ //output packet
+ if(av_interleaved_write_frame(output_context, packet) < 0){
+ break;
+ }
+ av_packet_unref(packet);
+
+ }
+
+ av_write_trailer(output_context);
+
+ return true;
+}
+
+
+//Get username/password for reddit account and bot. Plus a useragent string
+std::tuple parse_data_file(const raii::rjp_ptr& root){
+ RJP_search_res res = rjp_search_member(root.get(), "reddit", 0);
+ reddit::auth_data red_ret = reddit::parse_auth_data(res.value);
+
+ res = rjp_search_member(root.get(), "matrix", 0);
+ matrix::auth_data mat_ret = matrix::parse_auth_data(res.value);
+
+ res = rjp_search_member(root.get(), "useragent", 0);
+
+ return std::tuple(std::move(red_ret), std::move(mat_ret), raii::rjp_string(res.value));
+}
+//Read in file containing username/password details
+raii::rjp_ptr read_data_file(const char* file){
+ raii::filerd fp(file);
+ size_t blen;
+ if(!fp){
+ return nullptr;
+ }
+ blen = fp.length();
+ raii::string buff(blen);
+
+ [[maybe_unused]] size_t ign = fread(buff, blen, 1, fp);
+
+ buff[blen] = 0;
+
+ return raii::rjp_ptr(rjp_parse(buff));
+}
+
+size_t filewrite_response(char* ptr, size_t size, size_t nmemb, void* userdata){
+ fwrite(ptr, size, nmemb, reinterpret_cast(userdata));
+ return nmemb*size;
+}
+
+bool file_output_curl(raii::curler& curl, const raii::string_base& filename, const raii::string_base& url){
+ //Download the post's image
+ raii::filerd fp(filename, "w");
+ if(!fp)
+ fprintf(stderr, "unable to open file for writing\n");
+ curl.seturl(url);
+ curl.setopt(CURLOPT_BUFFERSIZE, 102400L);
+ curl.setopt(CURLOPT_NOPROGRESS, 1L);
+ curl.setopt(CURLOPT_FOLLOWLOCATION, 1L);
+ curl.setopt(CURLOPT_MAXREDIRS, 50L);
+ curl.setopt(CURLOPT_FAILONERROR, 1L);
+ curl.forcessl(CURL_SSLVERSION_TLSv1_2);
+ curl.setopt(CURLOPT_WRITEFUNCTION, filewrite_response);
+ curl.setopt(CURLOPT_WRITEDATA, fp.get());
+ int ret = curl.perform();
+ if(ret != CURLE_OK)
+ return false;
+ if(!fp.length())
+ return false;
+ return true;
+}
+
+
+void write_to_file(const char* file, const raii::string_base& data){
+ raii::filerd out(file, "a");
+ out.write(data);
+ out.write("\n"_ss);
+}
+
+int do_reddit_post(reddit::bot& redditbot, const matrix::bot& matbot, const raii::string_base& roomid, const raii::string_base& sub, reddit::time::period tp){
+ reddit::post reply;
+
+ {
+ int retries = 5;
+ do{
+ reply = redditbot.get_top_post(sub, reply.name(), tp);
+ if(reply.type() != reddit::post_type::text && reply.type() != reddit::post_type::link)
+ break;
+ --retries;
+ DEBUG_PRINT("Not an image.\nTODO, search for another\n");
+ if(reply.post_hint())
+ DEBUG_PRINT("post_hint: %s\n", reply.post_hint().get());
+ }while(retries);
+ }
+
+ write_to_file("post.log", reply.raw());
+ if(!reply){
+ fprintf(stderr, "Did not recieve a reply!\n");
+ return 3;
+ }
+
+ DEBUG_PRINT("name: %s\n", reply.name().get());
+ DEBUG_PRINT("title: %s\n", reply.title().get());
+ DEBUG_PRINT("author: %s\n", reply.author().get());
+ DEBUG_PRINT("mediaurl: %s\n", reply.mediaurl().get());
+ DEBUG_PRINT("posturl: %s\n", reply.posturl().get());
+
+ raii::curler curl;
+ if(reply.type() == reddit::post_type::image)
+ {
+ matbot.send_typing(roomid, true, 10000);
+ DEBUG_PRINT("Got an image\n");
+ file_output_curl(curl, "testout"_ss, reply.mediaurl());
+ auto img_data = matbot.upload_image("testout"_ss, reply.name());
+ auto val = matbot.send_image(roomid, img_data);
+ DEBUG_PRINT("image event: %s\n", val.get());
+ val = matbot.send_message(roomid, raii::string(reply.title() + "\n" + reply.posturl()));
+ DEBUG_PRINT("text event: %s\n", val.get());
+ remove("testout");
+ matbot.send_typing(roomid, false);
+ }
+ else if(reply.type() == reddit::post_type::video)
+ {
+ matbot.send_typing(roomid, true, 10000);
+ DEBUG_PRINT("Got a video\n");
+
+ if(reply.hosted_video_audio()){
+ DEBUG_PRINT("fuck reddit\n");
+ file_output_curl(curl, "video"_ss, reply.mediaurl());
+ if(!file_output_curl(curl, "audio"_ss, reply.hosted_video_audio())){
+ rename("video", "testout");
+ remove("audio");
+ }else{
+ DEBUG_PRINT("Remuxing audio and video\n");
+ bool b = mux_audio_video("audio"_ss, "video"_ss, "testout"_ss);
+ remove("audio");
+ remove("video");
+ if(!b){
+ matbot.send_message(roomid, "[ERROR] Unable to mux reddit hosted video/audio!"_ss);
+ matbot.send_typing(roomid, false);
+ return 5;
+ }
+ }
+ }else{
+ file_output_curl(curl, "testout"_ss, reply.mediaurl());
+ }
+
+ DEBUG_PRINT("Uploading video\n");
+ auto vid_data = matbot.upload_video("testout"_ss);
+ auto val = matbot.send_video(roomid, vid_data);
+ DEBUG_PRINT("video event: %s\n", val.get());
+ val = matbot.send_message(roomid, raii::string(reply.title() + "\n" + reply.posturl()));
+ DEBUG_PRINT("text event: %s\n", val.get());
+ remove("testout");
+ matbot.send_typing(roomid, false);
+ }
+ else if(reply.type() == reddit::post_type::audio){
+ matbot.send_typing(roomid, true, 10000);
+ DEBUG_PRINT("Got an audio file\n");
+ file_output_curl(curl, "testout"_ss, reply.mediaurl());
+ auto audio_data = matbot.upload_audio("testout"_ss, reply.name());
+ auto val = matbot.send_audio(roomid, audio_data);
+ DEBUG_PRINT("audio event: %s\n", val.get());
+ val = matbot.send_message(roomid, raii::string(reply.title() + "\n" + reply.posturl()));
+ DEBUG_PRINT("text event: %s\n", val.get());
+ remove("testout");
+ matbot.send_typing(roomid, false);
+ }
+ else if(reply.type() == reddit::post_type::link)
+ {
+ DEBUG_PRINT("Got a link\n");
+ return 0;
+ }
+ else
+ {
+ DEBUG_PRINT("post_hint: %s\n", reply.post_hint().get());
+ DEBUG_PRINT("TODO HANDLE THIS TYPE OF POST\n");
+ return 0;
+ }
+ return 0;
+}
+int main(){
+ REGISTER_LIBAV();
+ //Read data file
+ DEBUG_PRINT("reading data file \"data\"\n");
+ raii::rjp_ptr root = read_data_file("data");
+ if(!root){
+ fprintf(stderr, "Could not open data file\n");
+ return 1;
+ }
+
+ //Parse data file
+ auto [reddit_auth,matrix_auth,useragent] = parse_data_file(root);
+ if(!(reddit_auth && matrix_auth && useragent)){
+ fprintf(stderr, "Missing data field\n");
+ return 2;
+ }
+
+ //Get reddit post
+ reddit::bot redditbot(reddit_auth, useragent);
+ DEBUG_PRINT("reddit bot initialized\n");
+ matrix::bot matbot(matrix_auth, useragent);
+ DEBUG_PRINT("matrix bot initialized\n");
+ printf("%s\n", matbot.access_token().get());
+ auto sync_reply = matbot.sync(0); //initial sync
+ raii::string subreddit = "ProgrammerHumor";
+ auto start_time = std::chrono::system_clock::now();
+
+
+ bool should_quit = false;
+ auto sync_callback = [&](const matrix::bot& bot, const matrix::msg_info& msg)->void
+ {
+ printf("%s, %s\n%s\n%s: %s\n%d\n", msg.roomid.get(), msg.eventid.get(), msg.type.str(), msg.sender.get(), msg.body.get(), msg.age);
+ if(msg.age > 10000)
+ return;
+ if(msg.body == "!exit"_ss){
+ should_quit = true;
+ bot.send_message(msg.roomid, "[INFO] Shutting down..."_ss);
+ }else if(!strncmp(msg.body.get(), "!subreddit ", 11)){
+ if(msg.body.length() < 11){
+ bot.send_message(msg.roomid, "[ERROR] Missing argument to subreddit"_ss);
+ }else{
+ bot.send_message(msg.roomid, raii::string("[INFO] Set subreddit to \""_ss + (msg.body.get()+11) + "\""));
+ subreddit = msg.body.get()+11;
+ }
+ }else if(msg.body == "!lssub"_ss){
+ bot.send_message(msg.roomid, raii::string("Current subreddit is \"" + subreddit + "\""));
+ }else if(!strncmp(msg.body.get(), "!post ", 6)){
+ if(msg.body.length() > 6){
+ auto cur_time = std::chrono::system_clock::now();
+ std::chrono::duration elapsed = cur_time-start_time;
+ if(elapsed.count() >= 3600)
+ redditbot.refresh_token(reddit_auth);
+ if(!strcmp(msg.body.get()+6, "hour")){
+ do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::hour);
+ }else if(!strcmp(msg.body.get()+6, "day")){
+ do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::day);
+ }else if(!strcmp(msg.body.get()+6, "week")){
+ do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::week);
+ }else if(!strcmp(msg.body.get()+6, "month")){
+ do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::month);
+ }else if(!strcmp(msg.body.get()+6, "year")){
+ do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::year);
+ }else if(!strcmp(msg.body.get()+6, "all")){
+ do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::all);
+ }else{
+ bot.send_message(msg.roomid, raii::string("[ERROR] Unrecognized command arguments: \"" + msg.body + "\""));
+ }
+ }else{
+ do_reddit_post(redditbot, bot, msg.roomid, subreddit, reddit::time::hour);
+ }
+ }else if(msg.body == "!help"_ss){
+ bot.send_message(msg.roomid, "[INFO]\nThis is a matrix bot written by rexy712\nStill very much a WIP\nI can happily say that there are no memory leaks tho :)"_ss);
+ bot.send_message(msg.roomid, "Current list of commands:\n\n"
+ "!post : get a top post from a subreddit (default ProgrammerHumor). Specify hour,day,week,month,year,all.\n"
+ "!subreddit : set the current subreddit.\n"
+ "!lssub: get current subreddit.\n"
+ "!nipple: 'mxc://matrix.org/SYkDDTUwcfscliYTuIfYFIrx'\n"
+ "!license: print out a summary of the GNU Affero GPL\n"
+ "!fulllicense: print out the entire GNU Affero GPL\n"
+ "!source: link to the source code\n"
+ "!help: print this help\n"
+ "!exit: close the bot program"_ss);
+ }else if(msg.body == "!source"_ss){
+ bot.send_message(msg.roomid, "https://gitlab.com/rexy712/reddit_bot_thing"_ss);
+ }else if(msg.body == "!license"_ss){
+ bot.send_message(msg.roomid, "Copyright (C) 2019 rexy712.\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see ."_ss);
+ }else if(msg.body == "!fulllicense"_ss){
+ bot.send_message(msg.roomid, "Copyright (C) 2019 rexy712.\n\n GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. \n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate. Many developers of free software are heartened and\nencouraged by the resulting cooperation. However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community. It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server. Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals. This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n TERMS AND CONDITIONS\n\n 0. Definitions.\n\n `This License` refers to version 3 of the GNU Affero General Public License.\n\n `Copyright` also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n `The Program` refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as `you`. `Licensees` and\n`recipients` may be individuals or organizations.\n\n To `modify` a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a `modified version` of the\nearlier work or a work `based on` the earlier work.\n\n A `covered work` means either the unmodified Program or a work based\non the Program.\n\n To `propagate` a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n To `convey` a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n An interactive user interface displays `Appropriate Legal Notices`\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n 1. Source Code.\n\n The `source code` for a work means the preferred form of the work\nfor making modifications to it. `Object code` means any non-source\nform of a work.\n\n A `Standard Interface` means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n The `System Libraries` of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n`Major Component`, in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n The `Corresponding Source` for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n The Corresponding Source for a work in source code form is that\nsame work.\n\n 2. Basic Permissions.\n\n All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n Conveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n 4. Conveying Verbatim Copies.\n\n You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n 5. Conveying Modified Source Versions.\n\n You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n a) The work must carry prominent notices stating that you modified\n it, and giving a relevant date.\n\n b) The work must carry prominent notices stating that it is\n released under this License and any conditions added under section\n 7. This requirement modifies the requirement in section 4 to\n `keep intact all notices`.\n\n c) You must license the entire work, as a whole, under this\n License to anyone who comes into possession of a copy. This\n License will therefore apply, along with any applicable section 7\n additional terms, to the whole of the work, and all its parts,\n regardless of how they are packaged. This License gives no\n permission to license the work in any other way, but it does not\n invalidate such permission if you have separately received it.\n\n d) If the work has interactive user interfaces, each must display\n Appropriate Legal Notices; however, if the Program has interactive\n interfaces that do not display Appropriate Legal Notices, your\n work need not make them do so.\n\n A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n`aggregate` if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n 6. Conveying Non-Source Forms.\n\n You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n a) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by the\n Corresponding Source fixed on a durable physical medium\n customarily used for software interchange.\n\n b) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by a\n written offer, valid for at least three years and valid for as\n long as you offer spare parts or customer support for that product\n model, to give anyone who possesses the object code either (1) a\n copy of the Corresponding Source for all the software in the\n product that is covered by this License, on a durable physical\n medium customarily used for software interchange, for a price no\n more than your reasonable cost of physically performing this\n conveying of source, or (2) access to copy the\n Corresponding Source from a network server at no charge.\n\n c) Convey individual copies of the object code with a copy of the\n written offer to provide the Corresponding Source. This\n alternative is allowed only occasionally and noncommercially, and\n only if you received the object code with such an offer, in accord\n with subsection 6b.\n\n d) Convey the object code by offering access from a designated\n place (gratis or for a charge), and offer equivalent access to the\n Corresponding Source in the same way through the same place at no\n further charge. You need not require recipients to copy the\n Corresponding Source along with the object code. If the place to\n copy the object code is a network server, the Corresponding Source\n may be on a different server (operated by you or a third party)\n that supports equivalent copying facilities, provided you maintain\n clear directions next to the object code saying where to find the\n Corresponding Source. Regardless of what server hosts the\n Corresponding Source, you remain obligated to ensure that it is\n available for as long as needed to satisfy these requirements.\n\n e) Convey the object code using peer-to-peer transmission, provided\n you inform other peers where the object code and Corresponding\n Source of the work are being offered to the general public at no\n charge under subsection 6d.\n\n A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n A `User Product` is either (1) a `consumer product`, which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, `normally used` refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n `Installation Information` for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n 7. Additional Terms.\n\n `Additional permissions` are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n a) Disclaiming warranty or limiting liability differently from the\n terms of sections 15 and 16 of this License; or\n\n b) Requiring preservation of specified reasonable legal notices or\n author attributions in that material or in the Appropriate Legal\n Notices displayed by works containing it; or\n\n c) Prohibiting misrepresentation of the origin of that material, or\n requiring that modified versions of such material be marked in\n reasonable ways as different from the original version; or\n\n d) Limiting the use for publicity purposes of names of licensors or\n authors of the material; or\n\n e) Declining to grant rights under trademark law for use of some\n trade names, trademarks, or service marks; or\n\n f) Requiring indemnification of licensors and authors of that\n material by anyone who conveys the material (or modified versions of\n it) with contractual assumptions of liability to the recipient, for\n any liability that these contractual assumptions directly impose on\n those licensors and authors.\n\n All other non-permissive additional terms are considered `further\nrestrictions` within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n 8. Termination.\n\n You may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n 9. Acceptance Not Required for Having Copies.\n\n You are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n 10. Automatic Licensing of Downstream Recipients.\n\n Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\n An `entity transaction` is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n 11. Patents.\n\n A `contributor` is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's `contributor version`.\n\n A contributor's `essential patent claims` are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, `control` includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n In the following three paragraphs, a `patent license` is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To `grant` such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. `Knowingly relying` means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n A patent license is `discriminatory` if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n 12. No Surrender of Others' Freedom.\n\n If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n 13. Remote Network Interaction; Use with the GNU General Public License.\n\n Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software. This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n 14. Revised Versions of this License.\n\n The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n Each version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License `or any later version` applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n Later license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n 15. Disclaimer of Warranty.\n\n THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM `AS IS` WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n 16. Limitation of Liability.\n\n IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n 17. Interpretation of Sections 15 and 16.\n\n If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n END OF TERMS AND CONDITIONS\n\n How to Apply These Terms to Your New Programs\n\n If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n To do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe `copyright` line and a pointer to where the full notice is found.\n\n \n Copyright (C) \n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n\nAlso add information on how to contact you by electronic and paper mail.\n\n If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source. For example, if your program is a web application, its\ninterface could display a `Source` link that leads users to an archive\nof the code. There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n You should also get your employer (if you work as a programmer) or school,\nif any, to sign a `copyright disclaimer` for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n."_ss);
+ }else if(msg.body == "!nipple"_ss){
+ bot.send_image(msg.roomid, {"mxc://matrix.org/SYkDDTUwcfscliYTuIfYFIrx"_ss, "nipple.jpg"_ss, "image/jpeg"_ss, 40202, 512, 402, {}, 512, 402, 40202});
+ }
+ };
+ auto invite_callback = [&](const matrix::bot& bot, const matrix::membership_info& invite)->void{
+ printf("membership event:\nsender: %s\nrecipient: %s\n", invite.sender.get(), invite.recipient.get());
+ if(!strcmp(invite.recipient, "@rexybot:rexy712.chickenkiller.com"))
+ bot.accept_invite(invite);
+ };
+ matbot.set_message_callback(sync_callback);
+ matbot.set_membership_callback(invite_callback);
+
+ while(!should_quit){
+ sync_reply = matbot.sync(30000);
+ //DEBUG_PRINT("syncing\n");
+ DEBUG_PRINT("%s\n", sync_reply.get());
+ }
+
+}
diff --git a/include/matrix.hpp b/include/matrix.hpp
index 5618b69..02484dd 100644
--- a/include/matrix.hpp
+++ b/include/matrix.hpp
@@ -32,13 +32,13 @@
namespace matrix{
struct auth_data{
- raii::rjp_string bot_name;
- raii::rjp_string bot_pass;
+ raii::rjp_string name;
+ raii::rjp_string pass;
raii::rjp_string homeserver;
raii::rjp_string access_token;
operator bool(void)const{
- return (bot_name && bot_pass && homeserver);
+ return (name && pass && homeserver);
}
};
@@ -136,7 +136,7 @@ namespace matrix{
};
//main class
- class bot
+ class client
{
private:
class mat_url_list
@@ -207,18 +207,18 @@ namespace matrix{
raii::rjp_string m_next_batch; //string which tracks where we are in the server history
- std::function m_message_callback;
- std::function m_membership_callback;
+ std::function m_message_callback;
+ std::function m_membership_callback;
public:
- bot(const auth_data& a, const raii::string_base& useragent);
- bot(const auth_data& a, raii::string&& useragent);
- bot(const bot& b) = default;
- bot(bot&& b) = default;
- ~bot(void) = default;
+ client(const auth_data& a, const raii::string_base& useragent);
+ client(const auth_data& a, raii::string&& useragent);
+ client(const client& b) = default;
+ client(client&& b) = default;
+ ~client(void) = default;
- bot& operator=(const bot&) = default;
- bot& operator=(bot&&) = default;
+ client& operator=(const client&) = default;
+ client& operator=(client&&) = default;
//local getter
const raii::rjp_string& access_token(void)const;
@@ -268,7 +268,6 @@ namespace matrix{
raii::rjp_string redact_event(const raii::string_base& roomid, const raii::string_base& eventid, const raii::string_base& reason)const;
raii::rjp_string redact_event(const raii::string_base& roomid, const raii::string_base& eventid)const;
-
template
void set_message_callback(Func&& f){
diff --git a/include/reddit.hpp b/include/reddit.hpp
deleted file mode 100644
index 48ea562..0000000
--- a/include/reddit.hpp
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- This file is a part of rexy's matrix bot
- Copyright (C) 2019 rexy712
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see .
-*/
-
-#include "raii/rjp_string.hpp"
-#include "raii/curler.hpp"
-#include "raii/string_base.hpp"
-#include "raii/string.hpp"
-#include "raii/curler.hpp"
-
-namespace reddit{
- struct auth_data{
- raii::rjp_string bot_name;
- raii::rjp_string bot_pass;
- raii::rjp_string acc_name;
- raii::rjp_string acc_pass;
-
- operator bool(void)const{
- return (bot_name && bot_pass && acc_name && acc_pass);
- }
- };
-
-
- namespace time{
- class period{
- protected:
- const char* data;
- public:
- constexpr period(const char* d):
- data(d){}
- constexpr const char* get(void)const{
- return data;
- }
- };
- extern period hour;
- extern period day;
- extern period week;
- extern period month;
- extern period year;
- extern period all;
- }
-
- enum class post_type{
- image, link, text, video, audio, unrecognized
- };
-
- class post
- {
- private:
- enum post_flags{
- POST_FLAGS_NONE = 0,
- POST_FLAGS_CROSSPOSTED = 1
- };
- private:
- raii::string m_post;
- raii::rjp_string m_media_url;
- raii::string m_hosted_video_audio;
- raii::rjp_string m_author;
- raii::rjp_string m_post_hint;
- raii::rjp_string m_title;
- raii::rjp_string m_name;
- raii::rjp_string m_post_url;
- post_type m_type = post_type::unrecognized;
- int m_flags = POST_FLAGS_NONE;
-
- public:
- post(void) = default;
- post(const raii::string_base& p);
- post(raii::string_base&& p);
- post(const post& p) = default;
- post(post&& p) = default;
- ~post(void) = default;
-
- post& operator=(const raii::string_base& p);
- post& operator=(const post& p) = default;
- post& operator=(post&& p) = default;
-
- operator bool(void)const;
-
- const raii::string& raw(void)const;
- const raii::rjp_string& mediaurl(void)const;
- const raii::string& hosted_video_audio(void)const;
- const raii::rjp_string& posturl(void)const;
- const raii::rjp_string& author(void)const;
- const raii::rjp_string& post_hint(void)const;
- const raii::rjp_string& title(void)const;
- const raii::rjp_string& name(void)const;
- bool is_crosspost(void)const;
- post_type type(void)const;
- private:
- void _parse_post(void);
- static post_type _handle_reddit_hosted_video(RJP_value* data, raii::rjp_string& media_url, raii::string& audio_url);
- };
-
- class bot
- {
- private:
- raii::curler m_curl;
- raii::string m_useragent;
- raii::rjp_string m_access_token;
-
- public:
- bot(const auth_data& a, const raii::string_base& useragent);
- bot(const auth_data& a, raii::string_base&& useragent);
- bot(const bot& b);
- bot(bot&& b);
- ~bot(void) = default;
-
- bot& operator=(const bot& b);
- bot& operator=(bot&& b);
-
- const raii::rjp_string& access_token(void)const;
- const raii::string& useragent(void)const;
- void set_useragent(const raii::string_base&);
- void set_useragent(raii::string_base&&);
-
- void refresh_token(const auth_data& a);
-
- post get_new_post(const raii::string_base& subreddit);
- post get_new_post(const raii::string_base& subreddit, const raii::string_base& after);
- post get_hot_post(const raii::string_base& subreddit);
- post get_hot_post(const raii::string_base& subreddit, const raii::string_base& after);
- post get_rising_post(const raii::string_base& subreddit);
- post get_rising_post(const raii::string_base& subreddit, const raii::string_base& after);
- post get_best_post(const raii::string_base& subreddit);
- post get_best_post(const raii::string_base& subreddit, const raii::string_base& after);
- post get_top_post(const raii::string_base& subreddit, time::period period = time::day);
- post get_top_post(const raii::string_base& subreddit, const raii::string_base& after, time::period period = time::day);
- post get_controversial_post(const raii::string_base& subreddit, time::period period = time::day);
- post get_controversial_post(const raii::string_base& subreddit, const raii::string_base& after, time::period period = time::day);
-
- protected:
- static size_t _get_response_curl_callback(char* ptr, size_t size, size_t nmemb, void* userdata);
- static raii::curl_llist _create_auth_header(const raii::string_base& access_token);
- post _get_post(const raii::string_base& subreddit, const raii::string_base& category, const raii::string_base& extradata);
- void _setup_subreddit_get_curl(const raii::curl_llist& header, const raii::string_base& url, const raii::string_base& reply);
-
- static size_t _post_reply_curl_callback(char* ptr, size_t size, size_t nmemb, void* userdata);
- static raii::string _create_request_post_data(const raii::string_base& acc_name, const raii::string_base& acc_pass);
- static raii::string _create_request_userpwd(const raii::string_base& bot_name, const raii::string_base& bot_pass);
- void _setup_token_request_curl(const raii::string_base& userpwd, const raii::string_base& postdata, void* result);
-
- raii::string _request_access_token(const auth_data& a);
- raii::rjp_string _acquire_access_token(const auth_data& a);
- };
-
-
- auth_data parse_auth_data(RJP_value* root);
-
-}
diff --git a/makefile b/makefile
index 4dfd987..7b6aa23 100644
--- a/makefile
+++ b/makefile
@@ -26,7 +26,7 @@ CXXFLAGS:=-g -std=c++17 -Wall -pedantic -Wextra
all: CXXFLAGS+=-O0
release: CXXFLAGS+=-O2
LDFLAGS=
-LDLIBS:=-lcurl -lrjp -lavformat -lavcodec -lavutil -lswresample -lswscale -lfreeimageplus
+LDLIBS:=-lcurl -lrjp -lavformat -lavcodec -lavutil -lswresample -lswscale -lfreeimageplus -lpthread
STRIP:=strip
memchk:LDFLAGS+=-fsanitize=address -fno-omit-frame-pointer -fno-optimize-sibling-calls
diff --git a/src/matrix.cpp b/src/matrix.cpp
index b1c158d..7b1ed34 100644
--- a/src/matrix.cpp
+++ b/src/matrix.cpp
@@ -1,5 +1,5 @@
/**
- This file is a part of rexy's matrix bot
+ This file is a part of rexy's matrix client
Copyright (C) 2019 rexy712
This program is free software: you can redistribute it and/or modify
@@ -60,14 +60,14 @@ namespace matrix{
details[3].value};
}
- bot::bot(const auth_data& a, const raii::string_base& useragent):
+ client::client(const auth_data& a, const raii::string_base& useragent):
m_curl(),
m_useragent(useragent),
m_homeserver(a.homeserver)
{
_acquire_access_token(a);
}
- bot::bot(const auth_data& a, raii::string&& useragent):
+ client::client(const auth_data& a, raii::string&& useragent):
m_curl(),
m_useragent(std::move(useragent)),
m_homeserver(a.homeserver)
@@ -75,40 +75,40 @@ namespace matrix{
_acquire_access_token(a);
}
- const raii::rjp_string& bot::access_token(void)const{
+ const raii::rjp_string& client::access_token(void)const{
return m_access_token;
}
- const raii::rjp_string& bot::userid(void)const{
+ const raii::rjp_string& client::userid(void)const{
return m_userid;
}
- const raii::string& bot::useragent(void)const{
+ const raii::string& client::useragent(void)const{
return m_useragent;
}
- void bot::set_useragent(const raii::string_base& useragent){
+ void client::set_useragent(const raii::string_base& useragent){
m_useragent = useragent;
}
- void bot::set_useragent(raii::string&& useragent){
+ void client::set_useragent(raii::string&& useragent){
m_useragent = std::move(useragent);
}
- void bot::set_display_name(const raii::string_base& newname){
+ void client::set_display_name(const raii::string_base& newname){
raii::string reply = _put_curl(raii::string("{\"displayname\":\"" + newname + "\"}"), m_urls.displayname(), raii::curl_llist());
}
- void bot::set_profile_picture(const raii::string_base& media_url){
+ void client::set_profile_picture(const raii::string_base& media_url){
raii::string reply = _put_curl(raii::string("{\"avatar_url\":\"" + media_url + "\"}"), m_urls.profile_picture(), raii::curl_llist());
}
- raii::rjp_string bot::get_display_name(void)const{
+ raii::rjp_string client::get_display_name(void)const{
return _get_and_find(m_urls.displayname(), "displayname"_ss);
}
- raii::rjp_string bot::get_profile_picture(void)const{
+ raii::rjp_string client::get_profile_picture(void)const{
return _get_and_find(m_urls.profile_picture(), "avatar_url"_ss);
}
- raii::rjp_string bot::room_alias_to_id(const raii::string_base& alias)const{
+ raii::rjp_string client::room_alias_to_id(const raii::string_base& alias)const{
auto tmp = m_curl.encode(alias, alias.length());
return _get_and_find(raii::string(m_urls.alias_lookup() + tmp), "room_id"_ss);
}
- std::vector bot::list_rooms(void)const{
+ std::vector client::list_rooms(void)const{
std::vector ret;
raii::string reply = _get_curl(m_urls.room_list());
if(!reply)
@@ -128,7 +128,7 @@ namespace matrix{
return ret;
}
- raii::string bot::create_room(const raii::string_base& name, const raii::string_base& alias)const{
+ raii::string client::create_room(const raii::string_base& name, const raii::string_base& alias)const{
raii::string postdata;
if(alias)
postdata = "{\"name\": \"" + raii::json_escape(name) + "\",\"room_alias_name\": \"" + raii::json_escape(alias) + "\"}";
@@ -137,28 +137,28 @@ namespace matrix{
return _post_curl(postdata, m_urls.create_room(), raii::curl_llist());
}
- bool bot::join_room(const raii::string_base& roomid)const{
+ bool client::join_room(const raii::string_base& roomid)const{
return _post_curl(raii::string(), m_urls.join_room(m_homeserver, m_access_token, m_curl.encode(roomid)), raii::curl_llist());
}
- bool bot::leave_room(const raii::string_base& roomid)const{
+ bool client::leave_room(const raii::string_base& roomid)const{
return _post_curl(raii::string(), m_urls.leave_room(m_homeserver, m_access_token, m_curl.encode(roomid)), raii::curl_llist());
}
- bool bot::accept_invite(const membership_info& invite)const{
+ bool client::accept_invite(const membership_info& invite)const{
return join_room(invite.roomid);
}
- bool bot::reject_invite(const membership_info& invite)const{
+ bool client::reject_invite(const membership_info& invite)const{
return leave_room(invite.roomid);
}
- file_info bot::upload_file(const raii::string_base& filename)const{
+ file_info client::upload_file(const raii::string_base& filename)const{
return upload_file(filename, raii::static_string());
}
- file_info bot::upload_file(const raii::string_base& filename, const raii::string_base& alias)const{
+ file_info client::upload_file(const raii::string_base& filename, const raii::string_base& alias)const{
raii::filerd fd(filename);
if(!fd) return {};
return file_info{_upload_file(fd, raii::curl_llist{}), alias ? alias : filename, {}, fd.length()};
}
- image_info bot::upload_image(const raii::string_base& filename)const{
+ image_info client::upload_image(const raii::string_base& filename)const{
return upload_image(filename, raii::static_string());
}
#ifdef HAS_FREEIMAGE
@@ -201,7 +201,7 @@ namespace matrix{
}
return {};
}
- image_info bot::upload_image(const raii::string_base& filename, const raii::string_base& alias)const{
+ image_info client::upload_image(const raii::string_base& filename, const raii::string_base& alias)const{
image_info ret;
FREE_IMAGE_FORMAT type = fipImage::identifyFIF(filename.get());
ret.mimetype = FreeImage_GetFIFMimeType(type);
@@ -231,16 +231,16 @@ namespace matrix{
}
#else //HAS_FREEIMAGE
- image_info bot::upload_image(const raii::string_base& filename, const raii::string_base& alias)const{
+ image_info client::upload_image(const raii::string_base& filename, const raii::string_base& alias)const{
image_info ret = {};
ret = upload_file(filename, alias);
return ret;
}
#endif //HAS_FREEIMAGE
- video_info bot::upload_video(const raii::string_base& filename)const{
+ video_info client::upload_video(const raii::string_base& filename)const{
return upload_video(filename, raii::static_string());
}
- audio_info bot::upload_audio(const raii::string_base& filename)const{
+ audio_info client::upload_audio(const raii::string_base& filename)const{
return upload_audio(filename, raii::static_string());
}
#ifdef HAS_FFMPEG
@@ -327,7 +327,7 @@ namespace matrix{
return raii::string("video/" + raii::static_string(ctx->iformat->name, first - ctx->iformat->name));
return raii::string("video/" + raii::static_string(ctx->iformat->name));
}
- video_info bot::upload_video(const raii::string_base& filename, const raii::string_base& alias)const{
+ video_info client::upload_video(const raii::string_base& filename, const raii::string_base& alias)const{
video_info ret = {};
libav::fmt::input_context in(filename);
@@ -376,7 +376,7 @@ namespace matrix{
ret.filename = alias ? alias : filename;
return ret;
}
- audio_info bot::upload_audio(const raii::string_base& filename, const raii::string_base& alias)const{
+ audio_info client::upload_audio(const raii::string_base& filename, const raii::string_base& alias)const{
audio_info ret = {};
libav::fmt::input_context in(filename);
@@ -393,41 +393,41 @@ namespace matrix{
return ret;
}
#else //HAS_FFMPEG
- video_info bot::upload_video(const raii::string_base& filename, const raii::string_base& alias)const{
+ video_info client::upload_video(const raii::string_base& filename, const raii::string_base& alias)const{
video_info ret = {};
ret = upload_file(filename, alias);
return ret;
}
- audio_info bot::upload_audio(const raii::string_base& filename, const raii::string_base& alias)const{
+ audio_info client::upload_audio(const raii::string_base& filename, const raii::string_base& alias)const{
audio_info ret = {};
ret = upload_file(filename, alias);
return ret;
}
#endif //HAS_FFMPEG
- raii::rjp_string bot::send_file(const raii::string_base& room, const file_info& file)const{
+ raii::rjp_string client::send_file(const raii::string_base& room, const file_info& file)const{
return _send_message(room, detail::_file_body(file));
}
- raii::rjp_string bot::send_image(const raii::string_base& room, const image_info& image)const{
+ raii::rjp_string client::send_image(const raii::string_base& room, const image_info& image)const{
return _send_message(room, detail::_image_body(image));
}
- raii::rjp_string bot::send_video(const raii::string_base& room, const video_info& video)const{
+ raii::rjp_string client::send_video(const raii::string_base& room, const video_info& video)const{
return _send_message(room, detail::_video_body(video));
}
- raii::rjp_string bot::send_audio(const raii::string_base& room, const audio_info& audio)const{
+ raii::rjp_string client::send_audio(const raii::string_base& room, const audio_info& audio)const{
return _send_message(room, detail::_audio_body(audio));
}
- raii::rjp_string bot::send_message(const raii::string_base& room, const raii::string_base& text)const{
+ raii::rjp_string client::send_message(const raii::string_base& room, const raii::string_base& text)const{
return _send_message(room, detail::_message_body(text));
}
- void bot::send_typing(const raii::string_base& room, bool active, int timeout)const{
+ void client::send_typing(const raii::string_base& room, bool active, int timeout)const{
if(active)
_put_curl(raii::string("{\"timeout\":" + raii::itostr(timeout) + ",\"typing\":true}"), m_urls.typing(m_homeserver, m_access_token, m_curl.encode(room), m_curl.encode(m_userid)), raii::curl_llist());
else
_put_curl("{\"typing\":false}"_ss, m_urls.typing(m_homeserver, m_access_token, m_curl.encode(room), m_curl.encode(m_userid)), raii::curl_llist());
}
- raii::rjp_string bot::redact_event(const raii::string_base& roomid, const raii::string_base& eventid, const raii::string_base& reason)const{
+ raii::rjp_string client::redact_event(const raii::string_base& roomid, const raii::string_base& eventid, const raii::string_base& reason)const{
auto ret = _put_curl(raii::string("{\"reason\":\"" + reason + "\"}"), m_urls.redact(m_homeserver, m_access_token, m_curl.encode(roomid), m_curl.encode(eventid)), raii::curl_llist());
if(!ret) return {};
raii::rjp_ptr root(rjp_parse(ret.get()));
@@ -437,15 +437,15 @@ namespace matrix{
if(!res.value) return {};
return raii::rjp_string(res.value);
}
- raii::rjp_string bot::redact_event(const raii::string_base& roomid, const raii::string_base& eventid)const{
+ raii::rjp_string client::redact_event(const raii::string_base& roomid, const raii::string_base& eventid)const{
return redact_event(roomid, eventid, ""_ss);
}
- void bot::logout(void){
+ void client::logout(void){
_get_curl(m_urls.logout(m_homeserver, m_access_token));
m_urls.invalidate_accesstoken();
}
- raii::string bot::sync(size_t timeout){
+ raii::string client::sync(size_t timeout){
raii::string reply = _get_curl(m_urls.sync(m_homeserver, m_access_token, m_next_batch, raii::itostr(timeout)));
if(!reply)
@@ -474,7 +474,7 @@ namespace matrix{
Internal functions
********************************/
- void bot::_handle_membership_events(RJP_value* rooms){
+ void client::_handle_membership_events(RJP_value* rooms){
RJP_search_res res = rjp_search_member(rooms, "invite", 0);
if(res.value)
_handle_invites(res.value);
@@ -482,7 +482,7 @@ namespace matrix{
if(res.value)
_handle_other_membership(res.value);
}
- void bot::_handle_other_membership(RJP_value* join){
+ void client::_handle_other_membership(RJP_value* join){
for(RJP_value* roomid = rjp_get_member(join);roomid;roomid = rjp_next_member(roomid)){
RJP_search_res res = rjp_search_member(roomid, "timeline", 0);
if(!res.value) continue;
@@ -508,7 +508,7 @@ namespace matrix{
}
}
}
- void bot::_handle_invites(RJP_value* invites){
+ void client::_handle_invites(RJP_value* invites){
for(RJP_value* roomid = rjp_get_member(invites);roomid;roomid = rjp_next_member(roomid)){
RJP_search_res res = rjp_search_member(roomid, "invite_state", 0);
if(!res.value) continue;
@@ -525,7 +525,7 @@ namespace matrix{
}
}
}
- void bot::_handle_messages(RJP_value* messages){
+ void client::_handle_messages(RJP_value* messages){
RJP_search_res res = rjp_search_member(messages, "join", 0);
if(!res.value) return;
for(RJP_value* roomid = rjp_get_member(res.value);roomid;roomid = rjp_next_member(roomid)){
@@ -555,10 +555,10 @@ namespace matrix{
}
}
- void bot::_send_read_receipt(const raii::string_base& roomid, const raii::string_base& eventid)const{
+ void client::_send_read_receipt(const raii::string_base& roomid, const raii::string_base& eventid)const{
_post_curl(""_ss, m_urls.read_receipt(m_homeserver, m_access_token, m_curl.encode(roomid), m_curl.encode(eventid)), raii::curl_llist());
}
- raii::rjp_string bot::_upload_file(raii::filerd& fp, const raii::curl_llist& header)const{
+ raii::rjp_string client::_upload_file(raii::filerd& fp, const raii::curl_llist& header)const{
raii::string fileurl;
m_curl.postreq();
m_curl.setopt(CURLOPT_POSTFIELDS, NULL);
@@ -584,7 +584,7 @@ namespace matrix{
return res.value;
}
- raii::rjp_string bot::_send_message(const raii::string_base& room, const raii::string_base& msg)const{
+ raii::rjp_string client::_send_message(const raii::string_base& room, const raii::string_base& msg)const{
raii::rjp_string reply = _post_and_find(
msg,
m_urls.send(m_homeserver, m_access_token, m_curl.encode(room)),
@@ -592,13 +592,13 @@ namespace matrix{
"event_id"_ss);
return reply;
}
- size_t bot::_post_reply_curl_callback(char* ptr, size_t size, size_t nmemb, void* userdata){
+ size_t client::_post_reply_curl_callback(char* ptr, size_t size, size_t nmemb, void* userdata){
raii::string* data = reinterpret_cast(userdata);
(*data) += ptr;
return size*nmemb;
}
- raii::string bot::_get_curl(const raii::string_base& url)const{
+ raii::string client::_get_curl(const raii::string_base& url)const{
raii::string reply;
m_curl.getreq();
m_curl.seturl(url);
@@ -610,7 +610,7 @@ namespace matrix{
return {};
return reply;
}
- raii::string bot::_post_curl(const raii::string_base& postdata, const raii::string_base& url, const raii::curl_llist& header)const{
+ raii::string client::_post_curl(const raii::string_base& postdata, const raii::string_base& url, const raii::curl_llist& header)const{
raii::string reply;
m_curl.postreq();
m_curl.setopt(CURLOPT_POSTFIELDS, postdata.get());
@@ -637,7 +637,7 @@ namespace matrix{
src->data += to_copy;
return to_copy;
}
- raii::string bot::_put_curl(const raii::string_base& putdata, const raii::string_base& url, const raii::curl_llist& header)const{
+ raii::string client::_put_curl(const raii::string_base& putdata, const raii::string_base& url, const raii::curl_llist& header)const{
raii::string reply;
put_data data{putdata.get(), putdata.length()};
m_curl.putreq();
@@ -657,7 +657,7 @@ namespace matrix{
return {};
return reply;
}
- raii::rjp_string bot::_post_and_find(const raii::string_base& data, const raii::string_base& url,
+ raii::rjp_string client::_post_and_find(const raii::string_base& data, const raii::string_base& url,
const raii::curl_llist& header, const raii::string_base& target)const
{
raii::string reply = _post_curl(data, url, header);
@@ -665,13 +665,13 @@ namespace matrix{
return {};
return _curl_reply_search(reply, target);
}
- raii::rjp_string bot::_get_and_find(const raii::string_base& url, const raii::string_base& target)const{
+ raii::rjp_string client::_get_and_find(const raii::string_base& url, const raii::string_base& target)const{
raii::string reply = _get_curl(url);
if(!reply)
return {};
return _curl_reply_search(reply, target);
}
- raii::rjp_string bot::_curl_reply_search(const raii::string_base& reply, const raii::string_base& target)const{
+ raii::rjp_string client::_curl_reply_search(const raii::string_base& reply, const raii::string_base& target)const{
raii::rjp_ptr root(rjp_parse(reply));
if(!root)
return {};
@@ -680,7 +680,7 @@ namespace matrix{
return {};
return raii::rjp_string(res.value);
}
- void bot::_set_curl_defaults(void)const{
+ void client::_set_curl_defaults(void)const{
m_curl.setopt(CURLOPT_BUFFERSIZE, 102400L);
m_curl.setopt(CURLOPT_NOPROGRESS, 1L);
m_curl.setuseragent(m_useragent);
@@ -690,9 +690,9 @@ namespace matrix{
m_curl.setopt(CURLOPT_TCP_KEEPALIVE, 1L);
m_curl.setopt(CURLOPT_FAILONERROR, 1L);
}
- raii::string bot::_request_access_token(const auth_data& a)const{
+ raii::string client::_request_access_token(const auth_data& a)const{
CURLcode result;
- raii::string postdata("{\"type\":\"m.login.password\", \"user\":\"" + raii::json_escape(a.bot_name) + "\", \"password\":\"" + raii::json_escape(a.bot_pass) + "\"}");
+ raii::string postdata("{\"type\":\"m.login.password\", \"user\":\"" + raii::json_escape(a.name) + "\", \"password\":\"" + raii::json_escape(a.pass) + "\"}");
raii::string reply;
m_curl.seturl(m_urls.login());
@@ -708,7 +708,7 @@ namespace matrix{
return reply;
}
- void bot::_get_new_access_token(const auth_data& a){
+ void client::_get_new_access_token(const auth_data& a){
m_urls = mat_url_list(m_homeserver);
raii::string reply = _request_access_token(a);
if(!reply)
@@ -723,7 +723,7 @@ namespace matrix{
m_urls.repopulate_accesstoken(m_homeserver, m_access_token);
m_urls.repopulate_userid(m_homeserver, m_access_token, m_curl.encode(m_userid));
}
- void bot::_acquire_access_token(const auth_data& a){
+ void client::_acquire_access_token(const auth_data& a){
_set_curl_defaults();
if(a.access_token){
m_access_token = a.access_token;
@@ -750,28 +750,28 @@ namespace matrix{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- bot::mat_url_list::mat_url_list(const raii::string_base& homeserver){
+ client::mat_url_list::mat_url_list(const raii::string_base& homeserver){
_initial_populate(homeserver);
}
- bot::mat_url_list::mat_url_list(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& userid){
+ client::mat_url_list::mat_url_list(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& userid){
repopulate(homeserver, access_token, userid);
}
- void bot::mat_url_list::repopulate_accesstoken(const raii::string_base& homeserver, const raii::string_base& access_token){
+ void client::mat_url_list::repopulate_accesstoken(const raii::string_base& homeserver, const raii::string_base& access_token){
m_create_room = s_proto + homeserver + "/_matrix/client/r0/createRoom?access_token=" + access_token;
m_file_upload = s_proto + homeserver + "/_matrix/media/r0/upload?access_token=" + access_token;
m_room_list = s_proto + homeserver + "/_matrix/client/r0/joined_rooms?access_token=" + access_token;
m_whoami = s_proto + homeserver + "/_matrix/client/r0/account/whoami?access_token=" + access_token;
}
- void bot::mat_url_list::repopulate_userid(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& userid){
+ void client::mat_url_list::repopulate_userid(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& userid){
m_displayname = s_proto + homeserver + "/_matrix/client/r0/profile/" + userid + "/displayname?access_token=" + access_token;
m_profile_picture = s_proto + homeserver + "/_matrix/client/r0/profile/" + userid + "/avatar_url?access_token=" + access_token;
}
- void bot::mat_url_list::repopulate(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& userid){
+ void client::mat_url_list::repopulate(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& userid){
_initial_populate(homeserver);
repopulate_accesstoken(homeserver, access_token);
repopulate_userid(homeserver, access_token, userid);
}
- void bot::mat_url_list::invalidate_accesstoken(void){
+ void client::mat_url_list::invalidate_accesstoken(void){
m_create_room.reset();
m_file_upload.reset();
m_room_list.reset();
@@ -779,81 +779,81 @@ namespace matrix{
m_displayname.reset();
m_profile_picture.reset();
}
- const raii::string& bot::mat_url_list::create_room(void)const{
+ const raii::string& client::mat_url_list::create_room(void)const{
return m_create_room;
}
- const raii::string& bot::mat_url_list::file_upload(void)const{
+ const raii::string& client::mat_url_list::file_upload(void)const{
return m_file_upload;
}
- const raii::string& bot::mat_url_list::room_list(void)const{
+ const raii::string& client::mat_url_list::room_list(void)const{
return m_room_list;
}
- const raii::string& bot::mat_url_list::login(void)const{
+ const raii::string& client::mat_url_list::login(void)const{
return m_login;
}
- const raii::string& bot::mat_url_list::alias_lookup(void)const{
+ const raii::string& client::mat_url_list::alias_lookup(void)const{
return m_alias_lookup;
}
- const raii::string& bot::mat_url_list::whoami(void)const{
+ const raii::string& client::mat_url_list::whoami(void)const{
return m_whoami;
}
- const raii::string& bot::mat_url_list::displayname(void)const{
+ const raii::string& client::mat_url_list::displayname(void)const{
return m_displayname;
}
- const raii::string& bot::mat_url_list::profile_picture(void)const{
+ const raii::string& client::mat_url_list::profile_picture(void)const{
return m_profile_picture;
}
- raii::string bot::mat_url_list::logout(const raii::string_base& homeserver, const raii::string_base& access_token)const{
+ raii::string client::mat_url_list::logout(const raii::string_base& homeserver, const raii::string_base& access_token)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/logout?access_token=" + access_token);
}
- raii::string bot::mat_url_list::join_room(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::join_room(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/join?access_token=" + access_token);
}
- raii::string bot::mat_url_list::leave_room(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::leave_room(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/leave?access_token=" + access_token);
}
- raii::string bot::mat_url_list::sync(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& next_batch, const raii::string_base& timeout)const{
+ raii::string client::mat_url_list::sync(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& next_batch, const raii::string_base& timeout)const{
if(!next_batch)
return raii::string(s_proto + homeserver + "/_matrix/client/r0/sync?access_token=" + access_token + "&timeout=" + timeout);
return raii::string(s_proto + homeserver + "/_matrix/client/r0/sync?access_token=" + access_token + "&timeout=" + timeout + "&since=" + next_batch);
}
- raii::string bot::mat_url_list::read_receipt(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid, const raii::string_base& eventid)const{
+ raii::string client::mat_url_list::read_receipt(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid, const raii::string_base& eventid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/receipt/m.read/" + eventid + "?access_token=" + access_token);
}
- raii::string bot::mat_url_list::send(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::send(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/send/m.room.message?access_token=" + access_token);
}
- raii::string bot::mat_url_list::redact(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid, const raii::string_base& eventid)const{
+ raii::string client::mat_url_list::redact(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid, const raii::string_base& eventid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/redact/" + eventid + "/0?access_token=" + access_token);
}
- raii::string bot::mat_url_list::power_level(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::power_level(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/state/m.room.power_levels?access_token=" + access_token);
}
- raii::string bot::mat_url_list::presence(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& userid)const{
+ raii::string client::mat_url_list::presence(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& userid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/presence/" + userid + "/status?access_token=" + access_token);
}
- raii::string bot::mat_url_list::typing(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid, const raii::string_base& userid)const{
+ raii::string client::mat_url_list::typing(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid, const raii::string_base& userid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/typing/" + userid + "?access_token=" + access_token);
}
- raii::string bot::mat_url_list::kick(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::kick(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/kick?access_token=" + access_token);
}
- raii::string bot::mat_url_list::ban(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::ban(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/ban?access_token=" + access_token);
}
- raii::string bot::mat_url_list::unban(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::unban(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/unban?access_token=" + access_token);
}
- raii::string bot::mat_url_list::invite(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::invite(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/invite?access_token=" + access_token);
}
- raii::string bot::mat_url_list::room_members(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
+ raii::string client::mat_url_list::room_members(const raii::string_base& homeserver, const raii::string_base& access_token, const raii::string_base& roomid)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/rooms/" + roomid + "/members?access_token=" + access_token);
}
- raii::string bot::mat_url_list::password(const raii::string_base& homeserver, const raii::string_base& access_token)const{
+ raii::string client::mat_url_list::password(const raii::string_base& homeserver, const raii::string_base& access_token)const{
return raii::string(s_proto + homeserver + "/_matrix/client/r0/account/password?access_token=" + access_token);
}
- void bot::mat_url_list::_initial_populate(const raii::string_base& homeserver){
+ void client::mat_url_list::_initial_populate(const raii::string_base& homeserver){
m_alias_lookup = s_proto + homeserver + "/_matrix/client/r0/directory/room/";
m_login = s_proto + homeserver + "/_matrix/client/r0/login";
}
diff --git a/src/reddit.cpp b/src/reddit.cpp
deleted file mode 100644
index eb4b25c..0000000
--- a/src/reddit.cpp
+++ /dev/null
@@ -1,534 +0,0 @@
-/**
- This file is a part of rexy's matrix bot
- Copyright (C) 2019 rexy712
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see .
-*/
-
-#include "reddit.hpp"
-#include "raii/rjp_string.hpp"
-#include "raii/string.hpp"
-#include "raii/curler.hpp"
-#include "raii/rjp_ptr.hpp"
-#include "raii/static_string.hpp"
-
-#include //search
-#include
-
-//no idea if this covers everything reddit might dish out at me
-//there is no consistency in their content tagging. there are gifs marked as images, others as videos
-//they separate audio and video streams for their hosted videos, there is no true way to tell
-//what kind of content a post contains since the post_hint field might be completely nonexistent.
-//it's just a game of hacking together solutions each time reddit throws me a new type of unexpected complication.
-
-namespace reddit{
-
- namespace time{
- period hour = "hour";
- period day = "day";
- period week = "week";
- period month = "month";
- period year = "year";
- period all = "all";
- }
-
- auth_data parse_auth_data(RJP_value* root){
- static const char* account_names[2] = {"bot", "account"};
- static const char* account_fields[2] = {"username", "password"};
-
- auth_data ret;
- RJP_search_res accounts[2];
- RJP_search_res details[2];
- rjp_search_members(root, 2, account_names, accounts, 0);
-
- rjp_search_members(accounts[0].value, 2, account_fields, details, 0);
- ret.bot_name = details[0].value;
- ret.bot_pass = details[1].value;
-
- rjp_search_members(accounts[1].value, 2, account_fields, details, 0);
- ret.acc_name = details[0].value;
- ret.acc_pass = details[1].value;
-
- return ret;
- }
-
-
- static raii::rjp_string media_search(RJP_value* media){
- if(!media)
- return {};
- RJP_search_res res = rjp_search_member(media, "reddit_video", 0);
- if(!res.value)
- return raii::rjp_string{};
- res = rjp_search_member(res.value, "fallback_url", 0);
- if(!res.value)
- return raii::rjp_string{};
- return raii::rjp_string(res.value);
- }
- static raii::rjp_string preview_search(RJP_value* root){
- RJP_search_res media = rjp_search_member(root, "preview", 0);
- if(!media.value)
- return raii::rjp_string{};
- media = rjp_search_member(media.value, "reddit_video_preview", 0);
- if(!media.value)
- return raii::rjp_string{};
- media = rjp_search_member(media.value, "fallback_url", 0);
- if(!media.value)
- return raii::rjp_string{};
- return raii::rjp_string(media.value);
- }
- static bool check_reddit_media_domain(RJP_value* root){
- RJP_search_res res = rjp_search_member(root, "is_reddit_media_domain", 0);
- return (res.value && rjp_value_boolean(res.value));
- }
-
- static raii::rjp_string find_video_url(RJP_value* root){
- RJP_search_res media = rjp_search_member(root, "media", 0);
- if(raii::rjp_string res = media_search(media.value)){
- return res;
- }
- raii::rjp_string res = preview_search(root);
- return res;
- }
- static bool is_gifv(const raii::string_base& str){
- const char* s = str.get();
- size_t len = str.length();
- if(len > 5 &&
- *(s+len-1) == 'v' &&
- *(s+len-2) == 'f' &&
- *(s+len-3) == 'i' &&
- *(s+len-4) == 'g' &&
- *(s+len-5) == '.')
- {
- return true;
- }
- return false;
- }
- static bool has_extension(const raii::string_base& str){
- size_t i = 0;
- for(const char* p = str.get() + str.length() - 1;*p && i < 6;--p,++i){
- if(*p == '/')
- return false;
- else if(*p == '.')
- return true;
- }
- return false;
- }
- static bool is_gfycat_link(const raii::string_base& str){
- static const char gfycat[] = "gfycat.com";
- return *std::search(str.get(), str.get()+str.length(), gfycat, gfycat+sizeof(gfycat)-1) != 0;
- }
- static bool is_imgur_link(const raii::string_base& str){
- static const char imgur[] = "imgur.com";
- return *std::search(str.get(), str.get()+str.length(), imgur, imgur+sizeof(imgur)-1) != 0;
- }
- static bool is_direct_imgur_link(const raii::string_base& str){
- return is_imgur_link(str) && has_extension(str);
- }
-
-
-
- post::post(const raii::string_base& p):
- m_post(p)
- {
- _parse_post();
- }
- post::post(raii::string_base&& p):
- m_post(std::move(p)),
- m_type(post_type::unrecognized)
- {
- _parse_post();
- }
- post& post::operator=(const raii::string_base& p){
- post tmp(p);
- if(!tmp)
- return *this;
- return (*this = std::move(tmp));
- }
- post::operator bool(void)const{
- if(m_type == post_type::text)
- return (m_post_url && m_author && m_title && m_name);
- else
- return (m_post_url && m_media_url && m_author && m_title && m_name);
- }
-
- const raii::string& post::raw(void)const{
- return m_post;
- }
- const raii::rjp_string& post::mediaurl(void)const{
- return m_media_url;
- }
- const raii::string& post::hosted_video_audio(void)const{
- return m_hosted_video_audio;
- }
- const raii::rjp_string& post::posturl(void)const{
- return m_post_url;
- }
- const raii::rjp_string& post::author(void)const{
- return m_author;
- }
- const raii::rjp_string& post::post_hint(void)const{
- return m_post_hint;
- }
- const raii::rjp_string& post::title(void)const{
- return m_title;
- }
- const raii::rjp_string& post::name(void)const{
- return m_name;
- }
- bool post::is_crosspost(void)const{
- return (m_flags & POST_FLAGS_CROSSPOSTED);
- }
- post_type post::type(void)const{
- return m_type;
- }
- void post::_parse_post(void){
- raii::rjp_ptr root(rjp_parse(m_post));
- if(!root)
- return;
-
- static const char* search_items[] = {"url", "author", "post_hint", "title", "id", "crosspost_parent_list"};
- static constexpr size_t num_searches = sizeof(search_items)/sizeof(search_items[0]);
- RJP_search_res results[num_searches];
- RJP_search_res data = rjp_search_member(root.get(), "data", 0);
- if(!data.value) return;
- data = rjp_search_member(data.value, "children", 0);
- if(!data.value) return;
- data.value = rjp_get_element(data.value);
- if(!data.value) return;
- RJP_search_res kind = rjp_search_member(data.value, "kind", 0);
- if(!kind.value) return;
- data = rjp_search_member(data.value, "data", 0);
- if(!data.value) return;
-
- RJP_search_res& crosspost = results[5];
-
- rjp_search_members(data.value, num_searches, search_items, results, 0);
-
- //reddit will *sometimes* make the url field point to the crosspost parent's comments page.
- //so we just always assume that the true link is in the crosspost parent
- if(crosspost.value){
- m_flags |= POST_FLAGS_CROSSPOSTED;
- crosspost.value = rjp_get_element(crosspost.value);
- crosspost = rjp_search_member(crosspost.value, "url", 0);
- if(crosspost.value)
- m_media_url = crosspost.value;
- }else{
- m_media_url = results[0].value;
- }
- m_author = results[1].value;
- m_post_hint = results[2].value;
- m_title = results[3].value;
- m_name = raii::rjp_string(kind.value) + "_" + rjp_value_string(results[4].value);
- m_post_url = "https://redd.it/" + raii::rjp_string(results[4].value);
-
- if(m_post_hint){
- //handle simple image
- if(!strcmp(m_post_hint, "image")){
- m_type = post_type::image;
- }
- //handle link
- else if(!strcmp(m_post_hint, "link")){
- m_type = post_type::link;
-
- //imgur support
- if(is_imgur_link(m_media_url)){
- if(is_gifv(m_media_url)){ //gifv is a video
- if(raii::rjp_string tmp = preview_search(data.value)){
- m_media_url = std::move(tmp);
- m_type = post_type::video;
- }
- }else{
- //imgur links don't lead to the image source. adding .jpg to the link leads to the source
- //except when the link is to an album or to a gifv
- m_media_url += ".jpg"; //imgur is dumb
- m_type = post_type::image;
- }
- //gfycat support
- }else if(is_gfycat_link(m_media_url)){
- if(raii::rjp_string tmp = find_video_url(data.value)){
- m_media_url = std::move(tmp);
- m_type = post_type::video;
- }
- }
- }
- //handle hosted video
- else if(!strcmp(m_post_hint, "hosted:video")){
- m_type = _handle_reddit_hosted_video(data.value, m_media_url, m_hosted_video_audio);
- }
- else if(!strcmp(m_post_hint, "rich:video")){
- RJP_search_res media = rjp_search_member(data.value, "media", 0);
- raii::rjp_string res = media_search(media.value);
- if(res){
- m_type = post_type::video;
- m_media_url = std::move(res);
- return;
- }
- res = preview_search(data.value);
- if(res){
- m_type = post_type::video;
- m_media_url = std::move(res);
- return;
- }
- m_type = post_type::link;
- }
- else{
- //assume text post for other
- m_type = post_type::text;
- }
- }else if(is_direct_imgur_link(m_media_url)){
- m_type = post_type::image;
- return;
- }else if(check_reddit_media_domain(data.value)){
- m_type = _handle_reddit_hosted_video(data.value, m_media_url, m_hosted_video_audio);
- /*RJP_value* media = rjp_search_member(data.value, "media", 0).value;
- if(media && (rjp_value_type(media) != json_null))
- m_type = post_type::video;
- else
- m_type = post_type::image;
- //*/
- }else{
- m_media_url.reset();
- m_type = post_type::text;
- }
- }
- post_type post::_handle_reddit_hosted_video(RJP_value* data, raii::rjp_string& media_url, raii::string& audio_url){
-
- RJP_search_res media = rjp_search_member(data, "media", 0);
- RJP_search_res gif = rjp_search_member(media.value, "reddit_video", 0);
-
- //treat gif as image even though reddit thinks they're videos
- if(gif.value)
- gif = rjp_search_member(media.value, "is_gif", 0);
- if(gif.value && rjp_value_boolean(gif.value)){
- return post_type::image;
- }
- raii::rjp_string res = media_search(media.value);
- if(!res){
- res = preview_search(data);
- if(!res){
- return post_type::link;
- }
- }
- media_url = std::move(res);
-
- //reddit hosts audio and video separately. Meaning I have to find a way to manually recombine them.
- //this sets up a link to the audio source of the video. the video might not actually have audio. when downloading
- //from the audio link, always make sure to check for 404 errors.
- static constexpr char url_base[] = "https://v.redd.it/";
- static constexpr size_t url_base_len = sizeof(url_base)-1;
- char* end = strstr(media_url.get()+url_base_len, "/");
- if(!end)
- end = media_url.get()+media_url.length();
- size_t len = end - media_url.get();
- audio_url = raii::string(len + 6);
- memcpy(audio_url.get(), media_url.get(), len);
- memcpy(audio_url.get()+len, "/audio", 6);
- audio_url[len+6] = 0;
- return post_type::video;
- }
-
-
-
- bot::bot(const auth_data& a, const raii::string_base& useragent):
- m_curl(),
- m_useragent(useragent),
- m_access_token(_acquire_access_token(a)){}
- bot::bot(const auth_data& a, raii::string_base&& useragent):
- m_curl(),
- m_useragent(std::move(useragent)),
- m_access_token(_acquire_access_token(a)){}
- bot::bot(const bot& b):
- m_curl(b.m_curl),
- m_useragent(b.m_useragent),
- m_access_token(b.m_access_token){}
- bot::bot(bot&& b):
- m_curl(std::move(b.m_curl)),
- m_useragent(std::move(b.m_useragent)),
- m_access_token(std::move(b.m_access_token)){}
-
- bot& bot::operator=(bot&& b){
- m_useragent = std::move(b.m_useragent);
- m_access_token = std::move(b.m_access_token);
- return *this;
- }
- bot& bot::operator=(const bot& b){
- bot tmp(b);
- return *this = std::move(tmp);
- }
-
- const raii::rjp_string& bot::access_token(void)const{
- return m_access_token;
- }
- const raii::string& bot::useragent(void)const{
- return m_useragent;
- }
- void bot::set_useragent(const raii::string_base& s){
- m_useragent = s;
- }
- void bot::set_useragent(raii::string_base&& s){
- m_useragent = std::move(s);
- }
-
- void bot::refresh_token(const auth_data& a){
- m_access_token = _acquire_access_token(a);
- }
-
- post bot::get_new_post(const raii::string_base& subreddit){
- return _get_post(subreddit, "new"_ss, "limit=1"_ss);
- }
- post bot::get_new_post(const raii::string_base& subreddit, const raii::string_base& after){
- return _get_post(subreddit, "new"_ss, raii::string("limit=1&after=" + after));
- }
- post bot::get_hot_post(const raii::string_base& subreddit){
- return _get_post(subreddit, "hot"_ss, "limit=1"_ss);
- }
- post bot::get_hot_post(const raii::string_base& subreddit, const raii::string_base& after){
- return _get_post(subreddit, "hot"_ss, raii::string("limit=1&after=" + after));
- }
- post bot::get_rising_post(const raii::string_base& subreddit){
- return _get_post(subreddit, "rising"_ss, "limit=1"_ss);
- }
- post bot::get_rising_post(const raii::string_base& subreddit, const raii::string_base& after){
- return _get_post(subreddit, "rising"_ss, raii::string("limit=1&after=" + after));
- }
- post bot::get_best_post(const raii::string_base& subreddit){
- return _get_post(subreddit, "best"_ss, "limit=1"_ss);
- }
- post bot::get_best_post(const raii::string_base& subreddit, const raii::string_base& after){
- return _get_post(subreddit, "best"_ss, raii::string("limit=1&after=" + after));
- }
- post bot::get_top_post(const raii::string_base& subreddit, time::period period){
- raii::static_string pstr = period.get();
- return _get_post(subreddit, "top"_ss, raii::string("limit=1&t=" + pstr));
- }
- post bot::get_top_post(const raii::string_base& subreddit, const raii::string_base& after, time::period period){
- raii::static_string pstr = period.get();
- return _get_post(subreddit, "top"_ss, raii::string("limit=1&t=" + pstr + "&after=" + after));
- }
- post bot::get_controversial_post(const raii::string_base& subreddit, time::period period){
- raii::static_string pstr = period.get();
- return _get_post(subreddit, "controversial"_ss, raii::string("limit=1&t=" + pstr));
- }
- post bot::get_controversial_post(const raii::string_base& subreddit, const raii::string_base& after, time::period period){
- raii::static_string pstr = period.get();
- return _get_post(subreddit, "controversial"_ss, raii::string("limit=1&t=" + pstr + "&after=" + after));
- }
-
-
- post bot::_get_post(const raii::string_base& subreddit, const raii::string_base& category, const raii::string_base& extra){
- raii::string rep;
- static constexpr char url_base[] = "https://oauth.reddit.com/r/";
- raii::string url;
- if(extra)
- url = (url_base + subreddit) + "/" + category + "?" + extra;
- else
- url = (url_base + subreddit) + "/" + category;
- raii::curl_llist header(_create_auth_header(m_access_token));
- m_curl.reset();
- _setup_subreddit_get_curl(header, url, rep);
- m_curl.perform();
- return post(rep);
- }
- size_t bot::_get_response_curl_callback(char* ptr, size_t size, size_t nmemb, void* userdata){
- raii::rjp_string* reply = reinterpret_cast(userdata);
- (*reply) += ptr;
- return size*nmemb;
- }
- raii::curl_llist bot::_create_auth_header(const raii::string_base& access_token){
- return raii::curl_llist(raii::string("Authorization: bearer " + access_token));
- }
- void bot::_setup_subreddit_get_curl(const raii::curl_llist& header, const raii::string_base& url, const raii::string_base& reply){
- m_curl.seturl(url);
- m_curl.setopt(CURLOPT_BUFFERSIZE, 102400L);
- m_curl.setopt(CURLOPT_NOPROGRESS, 1L);
- m_curl.setopt(CURLOPT_MAXREDIRS, 50L);
- m_curl.setopt(CURLOPT_FOLLOWLOCATION, 1L);
- m_curl.forcessl(CURL_SSLVERSION_TLSv1_2);
- m_curl.setopt(CURLOPT_TCP_KEEPALIVE, 1L);
- m_curl.setheader(header);
- m_curl.setuseragent(m_useragent);
- m_curl.setopt(CURLOPT_WRITEFUNCTION, _get_response_curl_callback);
- m_curl.setopt(CURLOPT_WRITEDATA, &reply);
- m_curl.setopt(CURLOPT_FAILONERROR, 1L);
- }
-
- size_t bot::_post_reply_curl_callback(char* ptr, size_t size, size_t nmemb, void* userdata){
- raii::string* data = reinterpret_cast(userdata);
- (*data) += ptr;
- return size*nmemb;
- }
- //Create reddit login data
- raii::string bot::_create_request_post_data(const raii::string_base& account_name, const raii::string_base& account_pass){
- return raii::string("grant_type=password&username=" + account_name + "&password=" + account_pass);
- }
- //Setup login data for reddit bot
- raii::string bot::_create_request_userpwd(const raii::string_base& bot_name, const raii::string_base& bot_pass){
- return raii::string(bot_name + ":" + bot_pass);
- }
- void bot::_setup_token_request_curl(const raii::string_base& userpwd, const raii::string_base& postdata, void* result){
- static constexpr char reddit_token_address[] = "https://www.reddit.com/api/v1/access_token";
- m_curl.setopt(CURLOPT_BUFFERSIZE, 102400L);
- m_curl.seturl(reddit_token_address);
- m_curl.setopt(CURLOPT_NOPROGRESS, 1L);
- m_curl.setuserpwd(userpwd);
- m_curl.setpostdata(postdata);
- m_curl.setuseragent(m_useragent);
- m_curl.setheader(raii::curl_llist());
- m_curl.setopt(CURLOPT_MAXREDIRS, 50L);
- m_curl.setopt(CURLOPT_FOLLOWLOCATION, 1L);
- m_curl.forcessl(CURL_SSLVERSION_TLSv1_2);
- m_curl.setopt(CURLOPT_CUSTOMREQUEST, "POST");
- m_curl.setopt(CURLOPT_TCP_KEEPALIVE, 1L);
- m_curl.setopt(CURLOPT_WRITEFUNCTION, _post_reply_curl_callback);
- m_curl.setopt(CURLOPT_WRITEDATA, result);
- m_curl.setopt(CURLOPT_FAILONERROR, 1L);
- }
-
- raii::string bot::_request_access_token(const auth_data& auth){
- CURLcode result;
-
- //URL encode the POST data
- raii::curl_string acc_name = m_curl.encode(auth.acc_name, auth.acc_name.length());
- raii::curl_string acc_pass = m_curl.encode(auth.acc_pass, auth.acc_pass.length());
-
- //unify the post data, clean up remnants
- raii::string postdata = _create_request_post_data(acc_name, acc_pass);
- acc_name.reset();
- acc_pass.reset();
-
- //Unify the username/password
- raii::string userpwd = _create_request_userpwd(auth.bot_name, auth.bot_pass);
-
- //Load curl with data then run POST operation
- raii::string reply;
- _setup_token_request_curl(userpwd, postdata, &reply);
- result = m_curl.perform();
-
- if(result != CURLE_OK)
- return {};
- return reply;
- }
-
- raii::rjp_string bot::_acquire_access_token(const auth_data& a){
- raii::string reply = _request_access_token(a);
- if(!reply)
- return raii::rjp_string{};
-
- raii::rjp_ptr root(rjp_parse(reply));
- if(!root)
- return raii::rjp_string{};
- RJP_search_res token = rjp_search_member(root.get(), "access_token", 0);
- return raii::rjp_string{token.value};
- }
-}
diff --git a/src/test.cpp b/src/test.cpp
index 6219947..4009b54 100644
--- a/src/test.cpp
+++ b/src/test.cpp
@@ -1,5 +1,5 @@
/**
- This file is a part of rexy's matrix bot
+ This file is a part of rexy's matrix client
Copyright (C) 2019 rexy712
This program is free software: you can redistribute it and/or modify
@@ -16,437 +16,59 @@
along with this program. If not, see .
*/
-#include
-#include
-#include //move
-#include
+//example of a client which responds to commands
+
+#include "matrix.hpp"
+#include "raii/static_string.hpp"
+
+#include
+#include
+#include
#include
-#include "common.hpp"
-
-#if defined(DEBUG_LEVEL) && DEBUG_LEVEL >= DBG_LEVEL_VERBOSE
-# define LIBAV_SET_LOG_LEVEL() av_log_set_level(AV_LOG_INFO)
-#else
-# define LIBAV_SET_LOG_LEVEL() av_log_set_level(AV_LOG_FATAL)
-#endif
-
-#include "raii/curler.hpp"
-#include "raii/filerd.hpp"
-#include "raii/rjp_string.hpp"
-#include "raii/string.hpp"
-#include "raii/rjp_ptr.hpp"
-#include "raii/static_string.hpp"
-#include "reddit.hpp"
-#include "matrix.hpp"
-
-extern "C"{
-# include //sws_scale
-# include //av_image_alloc
-}
-#include "libav/packet.hpp"
-#include "libav/fmt/context.hpp"
-
-bool find_avformat_stream(AVFormatContext* output_context, const AVFormatContext* input_context, int* input_index, int* output_index, int codec_type){
- for(size_t i = 0;i < input_context->nb_streams;++i){
- if(input_context->streams[i]->codecpar->codec_type == codec_type){
- (*input_index) = i;
-
- AVStream* in_stream = input_context->streams[i];
- AVStream* out_stream = avformat_new_stream(output_context, NULL);
- (*output_index) = out_stream->index;
- avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
- out_stream->codecpar->codec_tag = 0;
-
- return true;
- }
- }
- return false;
-}
-bool find_audio_stream(AVFormatContext* output_context, const AVFormatContext* audio_context, int* audio_in_stream, int* audio_out_stream){
- return find_avformat_stream(output_context, audio_context, audio_in_stream, audio_out_stream, AVMEDIA_TYPE_AUDIO);
-}
-bool find_video_stream(AVFormatContext* output_context, const AVFormatContext* video_context, int* video_in_stream, int* video_out_stream){
- return find_avformat_stream(output_context, video_context, video_in_stream, video_out_stream, AVMEDIA_TYPE_VIDEO);
-}
-
-bool get_frame(AVFormatContext* ctx, int ctx_index, AVPacket* pkt){
- if(av_read_frame(ctx, pkt) >= 0){
- do{
- if(pkt->stream_index == ctx_index){
- return true;
- }
- av_packet_unref(pkt);
- }while(av_read_frame(ctx, pkt) >= 0);
- }
- return false;
-}
-int64_t correct_dts(AVFormatContext* output_context, AVPacket* packet, int64_t last_dts){
- if(packet->dts < (last_dts + !(output_context->oformat->flags & AVFMT_TS_NONSTRICT)) && packet->dts != AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE){
- int64_t next_dts = last_dts+1;
- if(packet->pts >= packet->dts){
- packet->pts = FFMAX(packet->pts, next_dts);
- }
- if(packet->pts == AV_NOPTS_VALUE){
- packet->pts = next_dts;
- }
- packet->dts = next_dts;
- }
- return packet->dts;
-}
-//a lot copied from a github repo, but with all deprecation warnings fixed.
-//no idea how the one guy managed to figure out all this with the minimal and conflicting documentation for ffmpeg and libav
-//with the new code that fixes invalid input pts/dts, now the output framerate/bitrate is off
-bool mux_audio_video(const raii::string_base& audio_file, const raii::string_base& video_file, const raii::string_base& output_file){
- REGISTER_LIBAV();
- LIBAV_SET_LOG_LEVEL();
-
- libavfmt::input_context audio_context(audio_file);
- libavfmt::input_context video_context(video_file);
- libavfmt::output_context output_context(output_file, "mp4");
- int video_index_in = -1, audio_index_in = -1;
- int video_index_out = -1, audio_index_out = -1;
-
- if(!find_audio_stream(output_context, audio_context, &audio_index_in, &audio_index_out) ||
- !find_video_stream(output_context, video_context, &video_index_in, &video_index_out))
+void sync_fn(matrix::client client, std::atomic_bool& should_quit){
+ client.set_message_callback([&](const matrix::client& client, const matrix::msg_info& msg)->void
{
- fprintf(stderr, "Unable to find input stream in\n");
- return false;
- }
-
- if(avformat_write_header(output_context, NULL) < 0){
- return false;
- }
-
- int64_t video_pts = 0, audio_pts = 0;
-
- //took me 2 days to realize I had to initialize these to the smallest possible int64 value instead of just 0
- int64_t last_video_dts, last_audio_dts;
- last_video_dts = last_audio_dts = AV_NOPTS_VALUE;
-
- while(true){
- libav::packet packet;
- int64_t* last_dts;
- AVFormatContext* in_context;
- int stream_index = 0;
- AVStream* in_stream, *out_stream;
-
- //Read in a frame from the next stream
- if(av_compare_ts(video_pts, video_context->streams[video_index_in]->time_base,
- audio_pts, audio_context->streams[audio_index_in]->time_base) <= 0)
- {
- //video
- last_dts = &last_video_dts;
- in_context = video_context;
- stream_index = video_index_out;
-
- if(!get_frame(video_context, video_index_in, packet)){
- break;
- }
- video_pts = packet->pts;
- }else{
- //audio
- last_dts = &last_audio_dts;
- in_context = audio_context;
- stream_index = audio_index_out;
-
- if(!get_frame(audio_context, audio_index_in, packet)){
- break;
- }
- audio_pts = packet->pts;
+ if(msg.body == "!exit"_ss){
+ should_quit = true;
+ client.send_message(msg.roomid, "Shutting down..."_ss);
+ }else if(msg.body == "!info"_ss){
+ client.send_message(msg.roomid, "This is an example of a client which responds to commands!"_ss);
}
- in_stream = in_context->streams[packet->stream_index];
- out_stream = output_context->streams[stream_index];
+ });
- av_packet_rescale_ts(packet, in_stream->time_base, out_stream->time_base);
-
- (*last_dts) = correct_dts(output_context, packet, *last_dts);
-
- packet->pos = -1;
- packet->stream_index = stream_index;
-
- //output packet
- if(av_interleaved_write_frame(output_context, packet) < 0){
+ auto sync_reply = client.sync(0);
+ while(!should_quit){
+ sync_reply = client.sync(30000);
+ }
+}
+void keyboard_fn(matrix::client client, std::atomic_bool& should_quit){
+ char buffer[2048];
+ while(!should_quit){
+ fgets(buffer, 2048, stdin);
+ if(!strcmp(buffer, "!exit\n")){
+ should_quit = true;
break;
}
- av_packet_unref(packet);
-
+ client.send_message("!QbNLZNFSsqUXqQwtJp:rexy712.chickenkiller.com"_ss , raii::static_string(buffer));
}
-
- av_write_trailer(output_context);
-
- return true;
}
-
-//Get username/password for reddit account and bot. Plus a useragent string
-std::tuple parse_data_file(const raii::rjp_ptr& root){
- RJP_search_res res = rjp_search_member(root.get(), "reddit", 0);
- reddit::auth_data red_ret = reddit::parse_auth_data(res.value);
-
- res = rjp_search_member(root.get(), "matrix", 0);
- matrix::auth_data mat_ret = matrix::parse_auth_data(res.value);
-
- res = rjp_search_member(root.get(), "useragent", 0);
-
- return std::tuple(std::move(red_ret), std::move(mat_ret), raii::rjp_string(res.value));
-}
-//Read in file containing username/password details
-raii::rjp_ptr read_data_file(const char* file){
- raii::filerd fp(file);
- size_t blen;
- if(!fp){
- return nullptr;
- }
- blen = fp.length();
- raii::string buff(blen);
-
- [[maybe_unused]] size_t ign = fread(buff, blen, 1, fp);
-
- buff[blen] = 0;
-
- return raii::rjp_ptr(rjp_parse(buff));
-}
-
-size_t filewrite_response(char* ptr, size_t size, size_t nmemb, void* userdata){
- fwrite(ptr, size, nmemb, reinterpret_cast(userdata));
- return nmemb*size;
-}
-
-bool file_output_curl(raii::curler& curl, const raii::string_base& filename, const raii::string_base& url){
- //Download the post's image
- raii::filerd fp(filename, "w");
- if(!fp)
- fprintf(stderr, "unable to open file for writing\n");
- curl.seturl(url);
- curl.setopt(CURLOPT_BUFFERSIZE, 102400L);
- curl.setopt(CURLOPT_NOPROGRESS, 1L);
- curl.setopt(CURLOPT_FOLLOWLOCATION, 1L);
- curl.setopt(CURLOPT_MAXREDIRS, 50L);
- curl.setopt(CURLOPT_FAILONERROR, 1L);
- curl.forcessl(CURL_SSLVERSION_TLSv1_2);
- curl.setopt(CURLOPT_WRITEFUNCTION, filewrite_response);
- curl.setopt(CURLOPT_WRITEDATA, fp.get());
- int ret = curl.perform();
- if(ret != CURLE_OK)
- return false;
- if(!fp.length())
- return false;
- return true;
-}
-
-
-void write_to_file(const char* file, const raii::string_base& data){
- raii::filerd out(file, "a");
- out.write(data);
- out.write("\n"_ss);
-}
-
-int do_reddit_post(reddit::bot& redditbot, const matrix::bot& matbot, const raii::string_base& roomid, const raii::string_base& sub, reddit::time::period tp){
- reddit::post reply;
-
- {
- int retries = 5;
- do{
- reply = redditbot.get_top_post(sub, reply.name(), tp);
- if(reply.type() != reddit::post_type::text && reply.type() != reddit::post_type::link)
- break;
- --retries;
- DEBUG_PRINT("Not an image.\nTODO, search for another\n");
- if(reply.post_hint())
- DEBUG_PRINT("post_hint: %s\n", reply.post_hint().get());
- }while(retries);
- }
-
- write_to_file("post.log", reply.raw());
- if(!reply){
- fprintf(stderr, "Did not recieve a reply!\n");
- return 3;
- }
-
- DEBUG_PRINT("name: %s\n", reply.name().get());
- DEBUG_PRINT("title: %s\n", reply.title().get());
- DEBUG_PRINT("author: %s\n", reply.author().get());
- DEBUG_PRINT("mediaurl: %s\n", reply.mediaurl().get());
- DEBUG_PRINT("posturl: %s\n", reply.posturl().get());
-
- raii::curler curl;
- if(reply.type() == reddit::post_type::image)
- {
- matbot.send_typing(roomid, true, 10000);
- DEBUG_PRINT("Got an image\n");
- file_output_curl(curl, "testout"_ss, reply.mediaurl());
- auto img_data = matbot.upload_image("testout"_ss, reply.name());
- auto val = matbot.send_image(roomid, img_data);
- DEBUG_PRINT("image event: %s\n", val.get());
- val = matbot.send_message(roomid, raii::string(reply.title() + "\n" + reply.posturl()));
- DEBUG_PRINT("text event: %s\n", val.get());
- remove("testout");
- matbot.send_typing(roomid, false);
- }
- else if(reply.type() == reddit::post_type::video)
- {
- matbot.send_typing(roomid, true, 10000);
- DEBUG_PRINT("Got a video\n");
-
- if(reply.hosted_video_audio()){
- DEBUG_PRINT("fuck reddit\n");
- file_output_curl(curl, "video"_ss, reply.mediaurl());
- if(!file_output_curl(curl, "audio"_ss, reply.hosted_video_audio())){
- rename("video", "testout");
- remove("audio");
- }else{
- DEBUG_PRINT("Remuxing audio and video\n");
- bool b = mux_audio_video("audio"_ss, "video"_ss, "testout"_ss);
- remove("audio");
- remove("video");
- if(!b){
- matbot.send_message(roomid, "[ERROR] Unable to mux reddit hosted video/audio!"_ss);
- matbot.send_typing(roomid, false);
- return 5;
- }
- }
- }else{
- file_output_curl(curl, "testout"_ss, reply.mediaurl());
- }
-
- DEBUG_PRINT("Uploading video\n");
- auto vid_data = matbot.upload_video("testout"_ss);
- auto val = matbot.send_video(roomid, vid_data);
- DEBUG_PRINT("video event: %s\n", val.get());
- val = matbot.send_message(roomid, raii::string(reply.title() + "\n" + reply.posturl()));
- DEBUG_PRINT("text event: %s\n", val.get());
- remove("testout");
- matbot.send_typing(roomid, false);
- }
- else if(reply.type() == reddit::post_type::audio){
- matbot.send_typing(roomid, true, 10000);
- DEBUG_PRINT("Got an audio file\n");
- file_output_curl(curl, "testout"_ss, reply.mediaurl());
- auto audio_data = matbot.upload_audio("testout"_ss, reply.name());
- auto val = matbot.send_audio(roomid, audio_data);
- DEBUG_PRINT("audio event: %s\n", val.get());
- val = matbot.send_message(roomid, raii::string(reply.title() + "\n" + reply.posturl()));
- DEBUG_PRINT("text event: %s\n", val.get());
- remove("testout");
- matbot.send_typing(roomid, false);
- }
- else if(reply.type() == reddit::post_type::link)
- {
- DEBUG_PRINT("Got a link\n");
- return 0;
- }
- else
- {
- DEBUG_PRINT("post_hint: %s\n", reply.post_hint().get());
- DEBUG_PRINT("TODO HANDLE THIS TYPE OF POST\n");
- return 0;
- }
- return 0;
-}
int main(){
- REGISTER_LIBAV();
- //Read data file
- DEBUG_PRINT("reading data file \"data\"\n");
- raii::rjp_ptr root = read_data_file("data");
- if(!root){
- fprintf(stderr, "Could not open data file\n");
- return 1;
- }
+ const char* username = "username";
+ const char* password = "password";
+ const char* useragent = "rexy712s test bot";
+ const char* homeserver = "matrix.org";
+ matrix::auth_data auth{username, password, homeserver};
- //Parse data file
- auto [reddit_auth,matrix_auth,useragent] = parse_data_file(root);
- if(!(reddit_auth && matrix_auth && useragent)){
- fprintf(stderr, "Missing data field\n");
- return 2;
- }
+ matrix::client matclient(auth, useragent);
+ auto sync_reply = matclient.sync(0); //initial sync
- //Get reddit post
- reddit::bot redditbot(reddit_auth, useragent);
- DEBUG_PRINT("reddit bot initialized\n");
- matrix::bot matbot(matrix_auth, useragent);
- DEBUG_PRINT("matrix bot initialized\n");
- printf("%s\n", matbot.access_token().get());
- auto sync_reply = matbot.sync(0); //initial sync
- raii::string subreddit = "ProgrammerHumor";
- auto start_time = std::chrono::system_clock::now();
-
-
- bool should_quit = false;
- auto sync_callback = [&](const matrix::bot& bot, const matrix::msg_info& msg)->void
- {
- printf("%s, %s\n%s\n%s: %s\n%d\n", msg.roomid.get(), msg.eventid.get(), msg.type.str(), msg.sender.get(), msg.body.get(), msg.age);
- if(msg.age > 10000)
- return;
- if(msg.body == "!exit"_ss){
- should_quit = true;
- bot.send_message(msg.roomid, "[INFO] Shutting down..."_ss);
- }else if(!strncmp(msg.body.get(), "!subreddit ", 11)){
- if(msg.body.length() < 11){
- bot.send_message(msg.roomid, "[ERROR] Missing argument to subreddit"_ss);
- }else{
- bot.send_message(msg.roomid, raii::string("[INFO] Set subreddit to \""_ss + (msg.body.get()+11) + "\""));
- subreddit = msg.body.get()+11;
- }
- }else if(msg.body == "!lssub"_ss){
- bot.send_message(msg.roomid, raii::string("Current subreddit is \"" + subreddit + "\""));
- }else if(!strncmp(msg.body.get(), "!post ", 6)){
- if(msg.body.length() > 6){
- auto cur_time = std::chrono::system_clock::now();
- std::chrono::duration elapsed = cur_time-start_time;
- if(elapsed.count() >= 3600)
- redditbot.refresh_token(reddit_auth);
- if(!strcmp(msg.body.get()+6, "hour")){
- do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::hour);
- }else if(!strcmp(msg.body.get()+6, "day")){
- do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::day);
- }else if(!strcmp(msg.body.get()+6, "week")){
- do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::week);
- }else if(!strcmp(msg.body.get()+6, "month")){
- do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::month);
- }else if(!strcmp(msg.body.get()+6, "year")){
- do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::year);
- }else if(!strcmp(msg.body.get()+6, "all")){
- do_reddit_post(redditbot,bot,msg.roomid, subreddit, reddit::time::all);
- }else{
- bot.send_message(msg.roomid, raii::string("[ERROR] Unrecognized command arguments: \"" + msg.body + "\""));
- }
- }else{
- do_reddit_post(redditbot, bot, msg.roomid, subreddit, reddit::time::hour);
- }
- }else if(msg.body == "!help"_ss){
- bot.send_message(msg.roomid, "[INFO]\nThis is a matrix bot written by rexy712\nStill very much a WIP\nI can happily say that there are no memory leaks tho :)"_ss);
- bot.send_message(msg.roomid, "Current list of commands:\n\n"
- "!post : get a top post from a subreddit (default ProgrammerHumor). Specify hour,day,week,month,year,all.\n"
- "!subreddit : set the current subreddit.\n"
- "!lssub: get current subreddit.\n"
- "!nipple: 'mxc://matrix.org/SYkDDTUwcfscliYTuIfYFIrx'\n"
- "!license: print out a summary of the GNU Affero GPL\n"
- "!fulllicense: print out the entire GNU Affero GPL\n"
- "!source: link to the source code\n"
- "!help: print this help\n"
- "!exit: close the bot program"_ss);
- }else if(msg.body == "!source"_ss){
- bot.send_message(msg.roomid, "https://gitlab.com/rexy712/reddit_bot_thing"_ss);
- }else if(msg.body == "!license"_ss){
- bot.send_message(msg.roomid, "Copyright (C) 2019 rexy712.\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see ."_ss);
- }else if(msg.body == "!fulllicense"_ss){
- bot.send_message(msg.roomid, "Copyright (C) 2019 rexy712.\n\n GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. \n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate. Many developers of free software are heartened and\nencouraged by the resulting cooperation. However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community. It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server. Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals. This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n TERMS AND CONDITIONS\n\n 0. Definitions.\n\n `This License` refers to version 3 of the GNU Affero General Public License.\n\n `Copyright` also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n `The Program` refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as `you`. `Licensees` and\n`recipients` may be individuals or organizations.\n\n To `modify` a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a `modified version` of the\nearlier work or a work `based on` the earlier work.\n\n A `covered work` means either the unmodified Program or a work based\non the Program.\n\n To `propagate` a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n To `convey` a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n An interactive user interface displays `Appropriate Legal Notices`\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n 1. Source Code.\n\n The `source code` for a work means the preferred form of the work\nfor making modifications to it. `Object code` means any non-source\nform of a work.\n\n A `Standard Interface` means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n The `System Libraries` of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n`Major Component`, in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n The `Corresponding Source` for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n The Corresponding Source for a work in source code form is that\nsame work.\n\n 2. Basic Permissions.\n\n All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n Conveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n 4. Conveying Verbatim Copies.\n\n You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n 5. Conveying Modified Source Versions.\n\n You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n a) The work must carry prominent notices stating that you modified\n it, and giving a relevant date.\n\n b) The work must carry prominent notices stating that it is\n released under this License and any conditions added under section\n 7. This requirement modifies the requirement in section 4 to\n `keep intact all notices`.\n\n c) You must license the entire work, as a whole, under this\n License to anyone who comes into possession of a copy. This\n License will therefore apply, along with any applicable section 7\n additional terms, to the whole of the work, and all its parts,\n regardless of how they are packaged. This License gives no\n permission to license the work in any other way, but it does not\n invalidate such permission if you have separately received it.\n\n d) If the work has interactive user interfaces, each must display\n Appropriate Legal Notices; however, if the Program has interactive\n interfaces that do not display Appropriate Legal Notices, your\n work need not make them do so.\n\n A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n`aggregate` if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n 6. Conveying Non-Source Forms.\n\n You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n a) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by the\n Corresponding Source fixed on a durable physical medium\n customarily used for software interchange.\n\n b) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by a\n written offer, valid for at least three years and valid for as\n long as you offer spare parts or customer support for that product\n model, to give anyone who possesses the object code either (1) a\n copy of the Corresponding Source for all the software in the\n product that is covered by this License, on a durable physical\n medium customarily used for software interchange, for a price no\n more than your reasonable cost of physically performing this\n conveying of source, or (2) access to copy the\n Corresponding Source from a network server at no charge.\n\n c) Convey individual copies of the object code with a copy of the\n written offer to provide the Corresponding Source. This\n alternative is allowed only occasionally and noncommercially, and\n only if you received the object code with such an offer, in accord\n with subsection 6b.\n\n d) Convey the object code by offering access from a designated\n place (gratis or for a charge), and offer equivalent access to the\n Corresponding Source in the same way through the same place at no\n further charge. You need not require recipients to copy the\n Corresponding Source along with the object code. If the place to\n copy the object code is a network server, the Corresponding Source\n may be on a different server (operated by you or a third party)\n that supports equivalent copying facilities, provided you maintain\n clear directions next to the object code saying where to find the\n Corresponding Source. Regardless of what server hosts the\n Corresponding Source, you remain obligated to ensure that it is\n available for as long as needed to satisfy these requirements.\n\n e) Convey the object code using peer-to-peer transmission, provided\n you inform other peers where the object code and Corresponding\n Source of the work are being offered to the general public at no\n charge under subsection 6d.\n\n A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n A `User Product` is either (1) a `consumer product`, which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, `normally used` refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n `Installation Information` for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n 7. Additional Terms.\n\n `Additional permissions` are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n a) Disclaiming warranty or limiting liability differently from the\n terms of sections 15 and 16 of this License; or\n\n b) Requiring preservation of specified reasonable legal notices or\n author attributions in that material or in the Appropriate Legal\n Notices displayed by works containing it; or\n\n c) Prohibiting misrepresentation of the origin of that material, or\n requiring that modified versions of such material be marked in\n reasonable ways as different from the original version; or\n\n d) Limiting the use for publicity purposes of names of licensors or\n authors of the material; or\n\n e) Declining to grant rights under trademark law for use of some\n trade names, trademarks, or service marks; or\n\n f) Requiring indemnification of licensors and authors of that\n material by anyone who conveys the material (or modified versions of\n it) with contractual assumptions of liability to the recipient, for\n any liability that these contractual assumptions directly impose on\n those licensors and authors.\n\n All other non-permissive additional terms are considered `further\nrestrictions` within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n 8. Termination.\n\n You may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n 9. Acceptance Not Required for Having Copies.\n\n You are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n 10. Automatic Licensing of Downstream Recipients.\n\n Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\n An `entity transaction` is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n 11. Patents.\n\n A `contributor` is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's `contributor version`.\n\n A contributor's `essential patent claims` are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, `control` includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n In the following three paragraphs, a `patent license` is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To `grant` such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. `Knowingly relying` means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n A patent license is `discriminatory` if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n 12. No Surrender of Others' Freedom.\n\n If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n 13. Remote Network Interaction; Use with the GNU General Public License.\n\n Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software. This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n 14. Revised Versions of this License.\n\n The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n Each version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License `or any later version` applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n Later license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n 15. Disclaimer of Warranty.\n\n THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM `AS IS` WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n 16. Limitation of Liability.\n\n IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n 17. Interpretation of Sections 15 and 16.\n\n If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n END OF TERMS AND CONDITIONS\n\n How to Apply These Terms to Your New Programs\n\n If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n To do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe `copyright` line and a pointer to where the full notice is found.\n\n \n Copyright (C) \n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n\nAlso add information on how to contact you by electronic and paper mail.\n\n If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source. For example, if your program is a web application, its\ninterface could display a `Source` link that leads users to an archive\nof the code. There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n You should also get your employer (if you work as a programmer) or school,\nif any, to sign a `copyright disclaimer` for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n."_ss);
- }else if(msg.body == "!nipple"_ss){
- bot.send_image(msg.roomid, {"mxc://matrix.org/SYkDDTUwcfscliYTuIfYFIrx"_ss, "nipple.jpg"_ss, "image/jpeg"_ss, 40202, 512, 402, {}, 512, 402, 40202});
- }
- };
- auto invite_callback = [&](const matrix::bot& bot, const matrix::membership_info& invite)->void{
- printf("membership event:\nsender: %s\nrecipient: %s\n", invite.sender.get(), invite.recipient.get());
- if(!strcmp(invite.recipient, "@rexybot:rexy712.chickenkiller.com"))
- bot.accept_invite(invite);
- };
- matbot.set_message_callback(sync_callback);
- matbot.set_membership_callback(invite_callback);
-
- while(!should_quit){
- sync_reply = matbot.sync(30000);
- //DEBUG_PRINT("syncing\n");
- DEBUG_PRINT("%s\n", sync_reply.get());
- }
+ std::atomic_bool should_quit = false;
+ std::thread sync_thread(sync_fn, matclient, std::ref(should_quit));
+ std::thread key_thread(keyboard_fn, std::move(matclient), std::ref(should_quit));
+ //one of these threads will always hang until another input is recieved
+ sync_thread.join();
+ key_thread.join();
}