kandi background
Explore Kits

mastodon | Your self-hosted , globally interconnected microblogging | Blog library

 by   tootsuite Ruby Version: v3.4.1 License: AGPL-3.0

 by   tootsuite Ruby Version: v3.4.1 License: AGPL-3.0

Download this library from

kandi X-RAY | mastodon Summary

mastodon is a Ruby library typically used in Web Site, Blog applications. mastodon has no bugs, it has no vulnerabilities, it has a Strong Copyleft License and it has medium support. You can download it from GitHub.
Your self-hosted, globally interconnected microblogging community
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • mastodon has a medium active ecosystem.
  • It has 24411 star(s) with 4055 fork(s). There are 652 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 1883 open issues and 4289 have been closed. On average issues are closed in 47 days. There are 49 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of mastodon is v3.4.1
mastodon Support
Best in #Blog
Average in #Blog
mastodon Support
Best in #Blog
Average in #Blog

quality kandi Quality

  • mastodon has no bugs reported.
mastodon Quality
Best in #Blog
Average in #Blog
mastodon Quality
Best in #Blog
Average in #Blog

securitySecurity

  • mastodon has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
mastodon Security
Best in #Blog
Average in #Blog
mastodon Security
Best in #Blog
Average in #Blog

license License

  • mastodon is licensed under the AGPL-3.0 License. This license is Strong Copyleft.
  • Strong Copyleft licenses enforce sharing, and you can use them when creating open source projects.
mastodon License
Best in #Blog
Average in #Blog
mastodon License
Best in #Blog
Average in #Blog

buildReuse

  • mastodon releases are available to install and integrate.
mastodon Reuse
Best in #Blog
Average in #Blog
mastodon Reuse
Best in #Blog
Average in #Blog
Top functions reviewed by kandi - BETA

kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here

Get all kandi verified functions for this library.

Get all kandi verified functions for this library.

mastodon Key Features

[Project homepage 🐘](https://joinmastodon.org)

[Support the development via Patreon][patreon]

[View sponsors](https://joinmastodon.org/sponsors)

[Blog](https://blog.joinmastodon.org)

[Documentation](https://docs.joinmastodon.org)

[Browse Mastodon servers](https://joinmastodon.org/#getting-started)

[Browse Mastodon apps](https://joinmastodon.org/apps)

Ruby on Rails powers the REST API and other web pages

React.js and Redux are used for the dynamic parts of the interface

Node.js powers the streaming API

PostgreSQL 9.5+

Redis 4+

Ruby 2.5+

Node.js 12+

Golang bufio from websocket breaking after first read

copy iconCopydownload iconDownload
url := "wss://poa.st/api/v1/streaming/?stream=public"
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
    log.Fatal(err)
}
defer ws.Close()

for {
    _, p, err := ws.ReadMessage()
    if err != nil {
        log.Fatal(err)
    }
    // p is a []byte containing the JSON document.
    fmt.Printf("%s\n", p)
}
url := "wss://poa.st/api/v1/streaming/?stream=public"
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
    log.Fatal(err)
}
defer ws.Close()

for {
    // The JSON documents are objects containing two fields, 
    // the event type and the payload. The payload is a JSON
    // document itself.
    var e struct {
        Event   string
        Payload string
    }

    err := ws.ReadJSON(&e)
    if err != nil {
        log.Fatal(err)
    }
    // TODO: decode e.Payload based on e.Event
}
url := "wss://poa.st/api/v1/streaming/?stream=public"
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
    log.Fatal(err)
}
defer ws.Close()

for {
    _, p, err := ws.ReadMessage()
    if err != nil {
        log.Fatal(err)
    }
    // p is a []byte containing the JSON document.
    fmt.Printf("%s\n", p)
}
url := "wss://poa.st/api/v1/streaming/?stream=public"
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
    log.Fatal(err)
}
defer ws.Close()

for {
    // The JSON documents are objects containing two fields, 
    // the event type and the payload. The payload is a JSON
    // document itself.
    var e struct {
        Event   string
        Payload string
    }

    err := ws.ReadJSON(&e)
    if err != nil {
        log.Fatal(err)
    }
    // TODO: decode e.Payload based on e.Event
}

Start an async background daemon in a Python FastAPI app

copy iconCopydownload iconDownload
@app.on_event("startup")
async def startup_event() -> None:
    """tasks to do at server startup"""
    asyncio.create_task(Gatherer().start_metering_daemon())

How to unescape HTML 5 entities in Java (')

copy iconCopydownload iconDownload
final String unescapedText = HtmlEscape.unescapeHtml("'");
System.out.println(unescapedText);
'
<!-- https://mvnrepository.com/artifact/org.unbescape/unbescape -->
<dependency>
    <groupId>org.unbescape</groupId>
    <artifactId>unbescape</artifactId>
    <version>1.1.6.RELEASE</version>
</dependency>
final String unescapedText = HtmlEscape.unescapeHtml("&apos;");
System.out.println(unescapedText);
'
<!-- https://mvnrepository.com/artifact/org.unbescape/unbescape -->
<dependency>
    <groupId>org.unbescape</groupId>
    <artifactId>unbescape</artifactId>
    <version>1.1.6.RELEASE</version>
</dependency>
final String unescapedText = HtmlEscape.unescapeHtml("&apos;");
System.out.println(unescapedText);
'
<!-- https://mvnrepository.com/artifact/org.unbescape/unbescape -->
<dependency>
    <groupId>org.unbescape</groupId>
    <artifactId>unbescape</artifactId>
    <version>1.1.6.RELEASE</version>
</dependency>

Trying to scrape texts with the same divs and no other info

copy iconCopydownload iconDownload
raw_data = response.css(".directory__card")[0].css(".accounts-table__count::text").getall()
values = list(filter(lambda s: s != "", map(lambda s: s.strip(), raw_data)))

Unable to resolve hostname with docker-compose and podman

copy iconCopydownload iconDownload
version: '3'
services:

  db:
    restart: always
    image: postgres:9.6-alpine
    shm_size: 256mb
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      timeout: 45s
      interval: 10s
      retries: 10
    volumes:
      - ./postgres:/var/lib/postgresql/data
    environment:
      - POSTGRES_HOST_AUTH_METHOD=trust

  redis:
    restart: always
    image: redis:6.0-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      timeout: 45s
      interval: 10s
      retries: 10
    volumes:
      - ./redis:/data

#  es:
#    restart: always
#    image: docker.elastic.co/elasticsearch/elasticsearch-oss:6.8.10
#    environment:
#      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
#      - "cluster.name=es-mastodon"
#      - "discovery.type=single-node"
#      - "bootstrap.memory_lock=true"
#    networks:
#      - internal_network
#    healthcheck:
#      test: ["CMD-SHELL", "curl --silent --fail localhost:9200/_cluster/health || exit 1"]
#    volumes:
#      - ./elasticsearch:/usr/share/elasticsearch/data
#    ulimits:
#      memlock:
#        soft: -1
#        hard: -1

  web:
    #    build: .
    image: tootsuite/mastodon
    restart: always
    env_file: .env.production
    command: bash -c "rm -f /mastodon/tmp/pids/server.pid; bundle exec rails s -p 3000"
    healthcheck:
      test: ["CMD-SHELL", "wget -q --spider --proxy=off localhost:3000/health || exit 1"]
      timeout: 45s
      interval: 10s
      retries: 10
    ports:
      - "127.0.0.1:3000:3000"
    depends_on:
      - db
      - redis
#      - es
    volumes:
      - ./public/system:/mastodon/public/system

  streaming:
    build: .
    image: tootsuite/mastodon
    restart: always
    env_file: .env.production
    command: node ./streaming
    healthcheck:
      test: ["CMD-SHELL", "wget -q --spider --proxy=off localhost:4000/api/v1/streaming/health || exit 1"]
      timeout: 45s
      interval: 10s
      retries: 10
    ports:
      - "127.0.0.1:4000:4000"
    depends_on:
      - db
      - redis

  sidekiq:
    build: .
    image: tootsuite/mastodon
    restart: always
    env_file: .env.production
    command: bundle exec sidekiq
    depends_on:
      - db
      - redis
    volumes:
      - ./public/system:/mastodon/public/system
## Uncomment to enable federation with tor instances along with adding the following ENV variables
## http_proxy=http://privoxy:8118
## ALLOW_ACCESS_TO_HIDDEN_SERVICE=true
#  tor:
#    image: sirboops/tor
#    networks:
#      - external_network
#      - internal_network
#
#  privoxy:
#    image: sirboops/privoxy
#    volumes:
#      - ./priv-config:/opt/config
#    networks:
#      - external_network
#      - internal_network

Test using mock raises exception

copy iconCopydownload iconDownload
import unittest
import bot
from unittest.mock import patch


class TestBot(unittest.TestCase):
    @patch("bot.Mastodon")
    def test_bot(self, mastodon_mock):
        b = bot.Bot()
        breakpoint()
        mastodon_mock.return_value = Mock()
        mastodon_mock.status_post.assert_called_with(
            b.reply_to_toot("1", account_name="@fake", message="test")
        )
import os
from mastodon import Mastodon

class Bot(object):
    #   Set up Mastodon
    def __init__(self, access_token="", base_address=""):
        self.mastadon = Mastodon(
            access_token,
            base_address
        )

    def reply_to_toot(post_id, account_name, message=None, status_notifications=None):
        media_ids = []
        for fn in os.listdir(str(settings.INPUT_FOLDER)):
            if fn.endswith(('.jpeg', '.png')):
                print(Path(fn))
                image_dict = self.mastodon.media_post(str(settings.INPUT_FOLDER / fn))
                media_ids.append(image_dict["id"])
        if message is not None:
            parts = []
            total_len = str(len(message) // settings.MAX_MESSAGE_LENGTH + 1)
            count = 1
            split_lines = message.splitlines(True)
            while split_lines:
                message_part = "@" + account_name + " {}/".format(count) + total_len + "\n\n"
                while split_lines != [] and len(message_part) + len(split_lines[0]) < settings.MAX_MESSAGE_LENGTH:
                    message_part += split_lines[0]
                    split_lines = split_lines[1:]
                parts.append(message_part)
                count += 1
            for part in parts:
                print(part)
                post_id = self.mastodon.status_post(status=part, media_ids=media_ids, in_reply_to_id=post_id)
        else:
            while media_ids:
                self.mastodon.status_post(status=message, media_ids=media_ids[0:4], in_reply_to_id=post_id)
                media_ids = media_ids[4:]

import unittest
import bot
from unittest.mock import patch


class TestBot(unittest.TestCase):
    @patch("bot.Mastodon")
    def test_bot(self, mastodon_mock):
        b = bot.Bot()
        breakpoint()
        mastodon_mock.return_value = Mock()
        mastodon_mock.status_post.assert_called_with(
            b.reply_to_toot("1", account_name="@fake", message="test")
        )
import os
from mastodon import Mastodon

class Bot(object):
    #   Set up Mastodon
    def __init__(self, access_token="", base_address=""):
        self.mastadon = Mastodon(
            access_token,
            base_address
        )

    def reply_to_toot(post_id, account_name, message=None, status_notifications=None):
        media_ids = []
        for fn in os.listdir(str(settings.INPUT_FOLDER)):
            if fn.endswith(('.jpeg', '.png')):
                print(Path(fn))
                image_dict = self.mastodon.media_post(str(settings.INPUT_FOLDER / fn))
                media_ids.append(image_dict["id"])
        if message is not None:
            parts = []
            total_len = str(len(message) // settings.MAX_MESSAGE_LENGTH + 1)
            count = 1
            split_lines = message.splitlines(True)
            while split_lines:
                message_part = "@" + account_name + " {}/".format(count) + total_len + "\n\n"
                while split_lines != [] and len(message_part) + len(split_lines[0]) < settings.MAX_MESSAGE_LENGTH:
                    message_part += split_lines[0]
                    split_lines = split_lines[1:]
                parts.append(message_part)
                count += 1
            for part in parts:
                print(part)
                post_id = self.mastodon.status_post(status=part, media_ids=media_ids, in_reply_to_id=post_id)
        else:
            while media_ids:
                self.mastodon.status_post(status=message, media_ids=media_ids[0:4], in_reply_to_id=post_id)
                media_ids = media_ids[4:]

How to have a NavigationLink inside another NavigationLink

copy iconCopydownload iconDownload
struct DemoRowView: View {
    @State private var isProfile = false
    @State private var isActive = false
    var body: some View {
        HStack {
            Image(systemName: "person")
                .scaledToFit()
                .onTapGesture {
                    self.isProfile = true
                    self.isActive = true
                }
            Text("Thread description")
                .onTapGesture {
                    self.isProfile = false
                    self.isActive = true
                }
                .background(
                    NavigationLink(destination: self.destination(), isActive: $isActive) { EmptyView() }
                )
        }
        .buttonStyle(PlainButtonStyle())
    }

    @ViewBuilder
    private func destination() -> some View {
        if isProfile {
            ProfileView()
        } else {
            ThreadView()
        }
    }
}

postgres won't start when installing docker mastodon

copy iconCopydownload iconDownload
Error: Database is uninitialized and superuser password is not specified.
       You must specify POSTGRES_PASSWORD to a non-empty value for the
       superuser
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: example
      POSTGRES_DB: mastodon_production
      POSTGRES_USER: mastodon

PG::ConnectionBad: could not connect to server: No such file or directory
 DB_HOST=db                                                                                                                          
 DB_USER=mastodon                                                                                                                                     
 DB_NAME=mastodon_production                                                                                                                          
 DB_PASS=example  <--- (the one which is set in DB)                                                                                                                           
 DB_PORT=5432
Error: Database is uninitialized and superuser password is not specified.
       You must specify POSTGRES_PASSWORD to a non-empty value for the
       superuser
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: example
      POSTGRES_DB: mastodon_production
      POSTGRES_USER: mastodon

PG::ConnectionBad: could not connect to server: No such file or directory
 DB_HOST=db                                                                                                                          
 DB_USER=mastodon                                                                                                                                     
 DB_NAME=mastodon_production                                                                                                                          
 DB_PASS=example  <--- (the one which is set in DB)                                                                                                                           
 DB_PORT=5432
Error: Database is uninitialized and superuser password is not specified.
       You must specify POSTGRES_PASSWORD to a non-empty value for the
       superuser
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: example
      POSTGRES_DB: mastodon_production
      POSTGRES_USER: mastodon

PG::ConnectionBad: could not connect to server: No such file or directory
 DB_HOST=db                                                                                                                          
 DB_USER=mastodon                                                                                                                                     
 DB_NAME=mastodon_production                                                                                                                          
 DB_PASS=example  <--- (the one which is set in DB)                                                                                                                           
 DB_PORT=5432
Error: Database is uninitialized and superuser password is not specified.
       You must specify POSTGRES_PASSWORD to a non-empty value for the
       superuser
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: example
      POSTGRES_DB: mastodon_production
      POSTGRES_USER: mastodon

PG::ConnectionBad: could not connect to server: No such file or directory
 DB_HOST=db                                                                                                                          
 DB_USER=mastodon                                                                                                                                     
 DB_NAME=mastodon_production                                                                                                                          
 DB_PASS=example  <--- (the one which is set in DB)                                                                                                                           
 DB_PORT=5432

Community Discussions

Trending Discussions on mastodon
  • Golang bufio from websocket breaking after first read
  • Start an async background daemon in a Python FastAPI app
  • How to unescape HTML 5 entities in Java (&amp;apos;)
  • Trying to scrape texts with the same divs and no other info
  • Unable to resolve hostname with docker-compose and podman
  • Test using mock raises exception
  • How to have a NavigationLink inside another NavigationLink
  • push rejected Heroku Python Flask requirements failing exiv2==0.3.1
  • postgres won't start when installing docker mastodon
Trending Discussions on mastodon

QUESTION

Golang bufio from websocket breaking after first read

Asked 2022-Feb-08 at 22:49

I am trying to stream JSON text from a websocket. However after an initial read I noticed that the stream seems to break/disconnect. This is from a Pleroma server (think: Mastodon). I am using the default Golang websocket library.

package main

import (
    "bufio"
    "fmt"
    "log"

    "golang.org/x/net/websocket"
)

func main() {
    origin := "https://poa.st/"
    url := "wss://poa.st/api/v1/streaming/?stream=public"

    ws, err := websocket.Dial(url, "", origin)
    if err != nil {
        log.Fatal(err)
    }

    s := bufio.NewScanner(ws)
    for s.Scan() {
        line := s.Text()
        fmt.Println(line)
    }
}

After the initial JSON text response, the for-loop breaks. I would expect it to send a new message every few seconds.

What might be causing this? I am willing to switch to the Gorilla websocket library if I can use it with bufio.

Thanks!

ANSWER

Answered 2022-Feb-08 at 22:49

Although x/net/websocket connection has a Read method with the same signature as the Read method in io.Reader, the connection does not work like an io.Reader. The connection will not work as you expect when wrapped with a bufio.Scanner.

The poa.st endpoint sends a stream of messages where each message is a JSON document. Use the following code to read the messages using the Gorilla package:

url := "wss://poa.st/api/v1/streaming/?stream=public"
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
    log.Fatal(err)
}
defer ws.Close()

for {
    _, p, err := ws.ReadMessage()
    if err != nil {
        log.Fatal(err)
    }
    // p is a []byte containing the JSON document.
    fmt.Printf("%s\n", p)
}

The Gorilla package has a helper method for decoding JSON messages. Here's an example of how to use that method.

url := "wss://poa.st/api/v1/streaming/?stream=public"
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
    log.Fatal(err)
}
defer ws.Close()

for {
    // The JSON documents are objects containing two fields, 
    // the event type and the payload. The payload is a JSON
    // document itself.
    var e struct {
        Event   string
        Payload string
    }

    err := ws.ReadJSON(&e)
    if err != nil {
        log.Fatal(err)
    }
    // TODO: decode e.Payload based on e.Event
}

Source https://stackoverflow.com/questions/71041497

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install mastodon

You can download it from GitHub.
On a UNIX-like operating system, using your system’s package manager is easiest. However, the packaged Ruby version may not be the newest one. There is also an installer for Windows. Managers help you to switch between multiple Ruby versions on your system. Installers can be used to install a specific or multiple Ruby versions. Please refer ruby-lang.org for more information.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Consider Popular Blog Libraries
Try Top Libraries by tootsuite
Compare Blog Libraries with Highest Support
Compare Blog Libraries with Highest Quality
Compare Blog Libraries with Highest Security
Compare Blog Libraries with Permissive License
Compare Blog Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.