Compare commits

..

3 Commits

Author SHA1 Message Date
ChronosX88
cf15aae5ac
Implement thread list update feature 2022-04-19 02:33:56 +03:00
ChronosX88
a0e45d81ff
Implement thread view update feature 2022-04-19 02:03:47 +03:00
ChronosX88
987c48d530
Implement posting messages in thread 2022-04-19 01:23:30 +03:00
7 changed files with 211 additions and 112 deletions

View File

@ -93,6 +93,20 @@ class _MyHomePageState extends State<MyHomePage> {
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
actions: [
TextButton.icon(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Обновление списка тредов...')),
);
Provider.of<ThreadListModel>(context, listen: false).update();
},
label: const Text("Обновить"),
style: TextButton.styleFrom(
primary: Theme.of(context).colorScheme.onPrimary),
icon: Icon(Icons.sync))
],
),
body: Center(
child: Container(

View File

@ -1,18 +1,28 @@
import 'package:enough_mail/enough_mail.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wind/thread_model.dart';
class MessageItemView extends StatelessWidget {
const MessageItemView({Key? key, required this.item, required this.isOpPost})
const MessageItemView(
{Key? key,
required this.item,
required this.isOpPost,
required this.isLast})
: super(key: key);
final MessageItem item;
final bool isOpPost;
final bool isLast;
@override
Widget build(BuildContext context) {
return Container(
margin: this.isOpPost ? EdgeInsets.only(bottom: 10) : EdgeInsets.all(0),
margin: this.isOpPost
? EdgeInsets.only(bottom: 10, left: 10, right: 10, top: 16)
: isLast
? EdgeInsets.only(left: 10, right: 10, bottom: 16)
: EdgeInsets.only(left: 10, right: 10),
child: Card(
elevation: 5,
child: Column(
@ -81,6 +91,8 @@ class MessageItem {
final String date;
final String body;
MimeMessage? originalMessage;
MessageItem(
this.id, this.number, this.subject, this.author, this.date, this.body);
}

View File

@ -6,8 +6,8 @@ import 'package:tuple/tuple.dart';
class NNTPClient {
late WebSocketChannel _channel;
final Queue<_NNTPCommand> commandQueue = new Queue();
final List<String> tempBuffer = [];
final Queue<_NNTPCommand> _commandQueue = new Queue();
final List<String> _tempBuffer = [];
String? currentGroup;
@ -25,22 +25,22 @@ class NNTPClient {
var respLines = resp.split("\r\n");
if (respLines.last == "") respLines.removeLast(); // trailing empty line
if ((respLines.length > 1 || tempBuffer.isNotEmpty) &&
if ((respLines.length > 1 || _tempBuffer.isNotEmpty) &&
respLines.last.codeUnits.last != ".".codeUnits.first) {
// if it's multiline response and it doesn't contain dot in the end
// then looks like we need to wait for next message to concatenate with current msg
tempBuffer.add(resp);
_tempBuffer.add(resp);
return;
}
if (tempBuffer.isNotEmpty) {
tempBuffer.add(resp);
resp = tempBuffer.join();
if (_tempBuffer.isNotEmpty) {
_tempBuffer.add(resp);
resp = _tempBuffer.join();
respLines = resp.split("\r\n");
respLines.removeLast(); // trailing empty line
tempBuffer.clear();
_tempBuffer.clear();
}
var command = commandQueue.removeFirst();
var command = _commandQueue.removeFirst();
var respCode = int.parse(respLines[0].split(" ")[0]);
command.responseCompleter.complete(_CommandResponse(respCode, respLines));
});
@ -49,7 +49,7 @@ class NNTPClient {
Future<_CommandResponse> _sendCommand(
String command, List<String> args) async {
var cmd = _NNTPCommand(_CommandRequest(command, args));
commandQueue.add(cmd);
_commandQueue.add(cmd);
if (args.length > 0) {
_channel.sink.add("$command ${args.join(" ")}\r\n");
} else {
@ -155,6 +155,18 @@ class NNTPClient {
return threads;
}
Future<int> postArticle(MimeMessage message) async {
var resp = await _sendCommand("POST", []);
if (resp.responseCode != 340) return resp.responseCode;
var rawMessage = message.renderMessage() + "\r\n.\r\n";
_channel.sink.add(rawMessage);
var cmd = _NNTPCommand(_CommandRequest("POST", []));
_commandQueue.add(cmd);
resp = await cmd.response;
return resp.responseCode;
}
}
class _NNTPCommand {

View File

@ -6,6 +6,8 @@ class ThreadListModel extends ChangeNotifier {
String currentGroup = "";
NNTPClient? client;
Map<String, Map<int, List<ThreadItem>>> threads = {};
int _pageNum = -1;
List<ThreadItem> _curItems = [];
Future<void> selectNewsgroup(String name) async {
if (currentGroup == name) return;
@ -13,27 +15,29 @@ class ThreadListModel extends ChangeNotifier {
currentGroup = name;
await client!.selectGroup(name);
threads.putIfAbsent(name, () => {});
_curItems.clear();
_pageNum = -1;
notifyListeners();
}
Future<List<ThreadItem>> getNewThreads(
int perPage, int pageNum, bool clearCache) async {
Future<List<ThreadItem>> getNewThreads(bool clearCache) async {
if (currentGroup == "") return [];
List<ThreadItem> items = [];
_pageNum += 1;
if (clearCache) {
threads[currentGroup]?.clear();
}
if (threads[currentGroup]!.containsKey(pageNum)) {
items.addAll(threads[currentGroup]![pageNum]!);
if (threads[currentGroup]!.containsKey(_pageNum)) {
_curItems.addAll(threads[currentGroup]![_pageNum]!);
} else {
var resp = await client!.getNewThreads(perPage, pageNum);
var resp = await client!.getNewThreads(10, _pageNum);
resp.forEach((pair) {
var number = pair.item1;
var msg = pair.item2;
items.add(ThreadItem(
_curItems.add(ThreadItem(
msg.getHeaderValue("Message-Id")!,
number,
msg.getHeaderValue("Subject")!,
@ -42,9 +46,18 @@ class ThreadListModel extends ChangeNotifier {
msg.decodeTextPlainPart()!));
});
threads[currentGroup]![pageNum] = items;
if (resp.isEmpty) _pageNum -= 1;
threads[currentGroup]![_pageNum] = List.from(_curItems);
}
return items;
return _curItems;
}
void update() {
_curItems.clear();
_pageNum = -1;
threads[currentGroup]!.clear();
notifyListeners();
}
}

View File

@ -1,7 +1,6 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wind/thread_list_model.dart';
import 'package:wind/thread_screen.dart';
class ThreadListView extends StatefulWidget {
@override
@ -9,8 +8,6 @@ class ThreadListView extends StatefulWidget {
}
class ThreadListViewState extends State<ThreadListView> {
List<ThreadItem> _items = [];
int _pageNum = 0;
String _curGroup = "";
@override
@ -24,16 +21,13 @@ class ThreadListViewState extends State<ThreadListView> {
if (snapshot.hasData &&
snapshot.connectionState != ConnectionState.waiting) {
List<ThreadItem> data = List.from(snapshot.data!);
_items.addAll(data);
if (_items.isNotEmpty &&
_items.last.number != -100500 &&
data.isNotEmpty)
_items.add(ThreadItem("", -100500, "", "", "",
if (data.isNotEmpty && data.last.number != -100500)
data.add(ThreadItem("", -100500, "", "", "",
"")); // magic item (for button "load more")
return _curGroup != ""
? _threadView()
? _threadView(data)
: Center(
child: Text("Newsgroup is not selected",
child: Text("Новостная группа не выбрана",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16)));
} else if (snapshot.hasError) {
@ -46,22 +40,18 @@ class ThreadListViewState extends State<ThreadListView> {
Future<List<ThreadItem>> _fetchThreadList(BuildContext context) async {
var model = context.read<ThreadListModel>();
if (model.currentGroup != _curGroup) {
_items.clear();
_curGroup = model.currentGroup;
_pageNum = 0;
}
return await model.getNewThreads(10, _pageNum, false);
_curGroup = model.currentGroup;
return await model.getNewThreads(false);
}
Widget _threadView() {
return _items.isNotEmpty
Widget _threadView(List<ThreadItem> items) {
return items.isNotEmpty
? Scrollbar(
child: ListView.builder(
key: PageStorageKey("threadList"),
itemCount: _items.length,
itemCount: items.length,
itemBuilder: (context, index) {
if (_items[index].number == -100500) {
if (items[index].number == -100500) {
return Container(
height: 100,
padding: EdgeInsets.all(20),
@ -72,19 +62,18 @@ class ThreadListViewState extends State<ThreadListView> {
),
onPressed: () {
setState(() {
_pageNum += 1;
_items.removeLast();
items.removeLast();
});
},
child: Text('Load more'),
child: Text('Загрузить больше'),
),
);
} else
return ThreadListItemView(item: _items[index]);
return ThreadListItemView(item: items[index]);
}),
)
: Center(
child: Text("This newsgroup is empty",
child: Text("Эта новостная группа пуста",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)));
}
}

View File

@ -1,3 +1,4 @@
import 'package:enough_mail/enough_mail.dart';
import 'package:flutter/cupertino.dart';
import 'package:wind/message_item_view.dart';
import 'package:wind/nntp_client.dart';
@ -9,13 +10,15 @@ class ThreadModel extends ChangeNotifier {
Future<MessageItem> getPost(int number) async {
var msg = await client!.getPost(number);
return MessageItem(
var mi = MessageItem(
msg.getHeaderValue("Message-Id")!,
number,
msg.getHeaderValue("Subject")!,
msg.getHeaderValue("From")!,
msg.getHeaderValue("Date")!,
msg.decodeTextPlainPart()!);
mi.originalMessage = msg;
return mi;
}
Future<List<MessageItem>> getThread(int threadNumber) async {
@ -39,4 +42,19 @@ class ThreadModel extends ChangeNotifier {
return items;
}
Future<int> postMessage(MimeMessage opPost, String text) async {
var msg = MessageBuilder.buildSimpleTextMessage(
MailAddress.empty(), [], text,
subject: "Re: " + opPost.decodeSubject()!);
msg.setHeader("From", "anonymous");
msg.addHeader("In-Reply-To", opPost.getHeaderValue("Message-Id"));
msg.addHeader("References", opPost.getHeaderValue("Message-Id"));
msg.addHeader("Newsgroups", client!.currentGroup!);
return await client!.postArticle(msg);
}
void update() {
notifyListeners();
}
}

View File

@ -1,7 +1,7 @@
import 'package:enough_mail/mime_message.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wind/message_item_view.dart';
import 'package:wind/nntp_client.dart';
import 'package:wind/thread_list_view.dart';
import 'package:wind/thread_model.dart';
@ -23,39 +23,54 @@ class ThreadScreen extends StatefulWidget {
class ThreadScreenState extends State<ThreadScreen> {
ThreadScreenState(this.threadNumber);
late NNTPClient client;
late ThreadModel model;
late int threadNumber;
@override
Widget build(BuildContext context) {
client = context.read<NNTPClient>();
model = Provider.of<ThreadModel>(context, listen: false);
return Scaffold(
appBar: AppBar(
title: Text("Thread #${this.threadNumber}"),
title: Text("Тред #${this.threadNumber}"),
actions: [
TextButton.icon(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Обновление треда...')),
);
model.update();
},
label: const Text("Обновить"),
style: TextButton.styleFrom(
primary: Theme.of(context).colorScheme.onPrimary),
icon: Icon(Icons.sync))
],
),
body: Center(
child: Container(
width: 640,
child: FutureBuilder<List<MessageItem>>(
future: _fetch(context),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<MessageItem> data = List.from(snapshot.data!);
data.insert(1, MessageItem("reply", 0, "", "", "", "")); // reply
return _listView(data);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Center(child: CircularProgressIndicator());
},
),
width: 650,
child: Consumer<ThreadModel>(
builder: ((context, value, child) =>
FutureBuilder<List<MessageItem>>(
future: _fetch(context),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<MessageItem> data = List.from(snapshot.data!);
data.insert(
1, MessageItem("reply", 0, "", "", "", "")); // reply
return _listView(data);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Center(child: CircularProgressIndicator());
},
))),
)),
);
}
Future<List<MessageItem>> _fetch(BuildContext context) async {
var model = context.read<ThreadModel>();
List<MessageItem> posts = [];
var threadPosts = await model.getThread(threadNumber);
@ -71,25 +86,34 @@ class ThreadScreenState extends State<ThreadScreen> {
itemCount: data.length,
itemBuilder: (context, index) {
if (index == 1) {
return SendMessageForm();
return SendMessageForm(opPost: data[0].originalMessage!);
}
return MessageItemView(item: data[index], isOpPost: index == 0);
return MessageItemView(
item: data[index],
isOpPost: index == 0,
isLast: index == data.length - 1);
});
}
}
class SendMessageForm extends StatefulWidget {
const SendMessageForm({Key? key}) : super(key: key);
const SendMessageForm({Key? key, required this.opPost}) : super(key: key);
final MimeMessage opPost;
@override
SendMessageFormState createState() {
return SendMessageFormState();
return SendMessageFormState(opPost);
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class SendMessageFormState extends State<SendMessageForm> {
SendMessageFormState(this.opPost);
final MimeMessage opPost;
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
@ -102,50 +126,67 @@ class SendMessageFormState extends State<SendMessageForm> {
// Build a Form widget using the _formKey created above.
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Column(children: [
Consumer<ThreadModel>(
builder: ((context, value, child) => TextFormField(
controller: value.commentTextController,
minLines: 5,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(), labelText: "Comment"),
// The validator receives the text that the user has entered.
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
))),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState!.validate()) {
// If the form is valid, display a snackbar. In the real world,
// you'd often call a server or save the information in a database.
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Processing Data')),
);
child: Container(
margin: EdgeInsets.only(left: 16, right: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Column(children: [
Consumer<ThreadModel>(
builder: ((context, value, child) => TextFormField(
controller: value.commentTextController,
minLines: 5,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: "Комментарий"),
// The validator receives the text that the user has entered.
validator: (value) {
if (value == null || value.isEmpty) {
return 'Пожалуйста, введите текст';
}
return null;
},
child: const Text('Send'),
)
]))
]),
)
],
))),
Consumer<ThreadModel>(
builder: (((context, value, child) => Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState!.validate()) {
Provider.of<ThreadModel>(context,
listen: false)
.postMessage(opPost,
value.commentTextController.text)
.then((responseCode) {
if (responseCode == 240) {
ScaffoldMessenger.of(context)
.showSnackBar(
const SnackBar(
content: Text('Пост отправлен!')),
);
Provider.of<ThreadModel>(context,
listen: false)
.update();
}
});
value.commentTextController.text = "";
}
},
child: const Text('Отправить'),
)
])))),
)
]),
)
],
),
),
);
}